2

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?

M1X
  • 4,971
  • 10
  • 61
  • 123

4 Answers4

17

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.

some
  • 48,070
  • 14
  • 77
  • 93
  • 4
    No matter the reasons, this makes for an extremely frustrating development experience. Node should prioritize fixing this IMO. – Aditya Anand Jul 10 '20 at 05:38
  • @AdityaAnand: [there's a flag for that](https://stackoverflow.com/questions/64453859/directory-import-is-not-supported-resolving-es-modules-with-node-js/65588027#65588027). – Dan Dascalescu Jan 05 '21 at 23:31
2

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.

Amr Salama
  • 802
  • 1
  • 7
  • 19
1

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

// index.ts file.
import router from './routes.js';
Kory Heard
  • 41
  • 1
0

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()
}
C.Gochev
  • 1,837
  • 11
  • 21