M1X
M1X

Reputation: 5354

Node.js unable to import ES6 module

I'm trying to separate my routes to a separate module in routes.js and then importing in app.js. I'm getting a lot of errors in the console.

internal/modules/esm/default_resolve.js:96 let url = moduleWrapResolve(specifier, parentURL); ^ Error: Cannot find module /Users/rhoxh/Desktop/24/routes imported from /Users/rhoxh/Desktop/24/app.js at Loader.resolve [as _resolve] (internal/modules/esm/default_resolve.js:96:13) at Loader.resolve (internal/modules/esm/loader.js:73:33) at Loader.getModuleJob (internal/modules/esm/loader.js:147:40) at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:41:40) at link (internal/modules/esm/module_job.js:40:36) { code: 'ERR_MODULE_NOT_FOUND' }

routes.js

import express from 'express';

const router = express.Router();

router.get('/', (req, res) => {
  res.send('home page');
});

export default router;

app.js

import express from 'express';
import { router } from './routes';

const app = express();
const PORT = 8080;

app.listen(PORT, () => {
  console.log(`Server running at: http://localhost:${PORT}/`);
});

// Routes
app.use('/', router);

What am I doing wrong here?

Upvotes: 2

Views: 12202

Answers (4)

Amr Salama
Amr Salama

Reputation: 971

You can check this link it could help you https://github.com/nodejs/node/issues/27408

You can try to use --es-module-specifier-resolution=node as it says.

Upvotes: 2

Kory Heard
Kory Heard

Reputation: 41

For anyone looking for a typescript solution use the .js file extension of your transpiled files.

// index.ts file.
import router from './routes.js';

Upvotes: 1

some
some

Reputation: 49582

You need to use the full file name:

import router from './routes.js';

From the documentation:

module-name

The module to import from. This is often a relative or absolute path name to the .js file containing the module. Certain bundlers may permit or require the use of the extension; check your environment. Only single quoted and double quoted Strings are allowed.

Upvotes: 17

C.Gochev
C.Gochev

Reputation: 1922

You are destructuring your import yet you are exporting as default. When you import a default there is no need for destructuring

import router from './routes';

You can use destructuring when you are using either a named export

export const router = express.Router()

or you pull out a property from the default export

export default {
  router: express.Router()
}

Upvotes: 0

Related Questions