orion92
orion92

Reputation: 55

NodeJS: Cannot use import statement outside a module(already tried type :"module")

I have received a NodeJS application from client and trying to get it up and running. The very first issue I received is "Cannot use import statement outside a module". So, I tried including "type": "module" in package.json but it still is not working. Upon providing "nodemon src\server.js" command after including the above line, I get Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'D:\Projects\MyApp\APIs\src\app' imported from D:\Projects\MyApp\APIs\src\server.js

When I change

import app from './app';

with

import app from './app.js';

the error goes but it occurs for other imports. For example: Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'D:\Projects\MyApp\APIs\src\routes\user' imported from D:\Projects\MyApp\APIs\src\app.js

So again, if I change

import UserRoutes from './routes/v1/user/user';

with

import UserRoutes from './routes/v1/user/user.js';

the error vanishes for this import but again pops up for other import statement. There are many js files and they have been imported like this only. Do I need to include extension for all of them wherever they are imported or is there a way around to fix it? Node version I am using is 14.17.0

Upvotes: 0

Views: 682

Answers (1)

Apoorva Chikara
Apoorva Chikara

Reputation: 8783

You can resolve by using the node module structure :

Full Command :

node --experimental-modules --es-module-specifier-resolution=node app.js

For more details check this.

Upvotes: 1

Related Questions