0

I have been using CommonJS imports. Today I decided to try out ESM Imports but getting Cannot import A from B error message.

Here is class A

class A {
    static _initDefaults(app) {
        app.get('/', (_req, res) => {
            return res.status(200).send('Success');
        });
    }
    static initialize(app) {
        this._initDefaults(app);
    }
}
export default A;

Then in my server.js file I imported it as this

import A from './A'; //Error is thrown here

The error I keep getting back is this:

 Error [ERR_MODULE_NOT_FOUND]: Cannot find module 

'/Users/me/Documents/../.../a' imported from /Users/me/Documents/../../server.js
Did you mean to import ../a.js?

However I just noticed that if add the .js file extension the import works

import A from './A.js'; //This works
import A from './A'; //This doesn't work

In my package.json file I have this

{
 type:"module"
}

Is the file extension mandatory? How can I avoid always having to type the file extension unless absolutely necessary?

I usually don't type the file extension when using CommonJS unless I'm importing a json, html or css file

ololo
  • 1,326
  • 2
  • 14
  • 47
  • Yes, the file extension is necessary by default in ES6 modules (unless, of course, you name your file without an extension). You could tell nodejs to use a different module resolver, but you'd need to do so explicitly. – Bergi Jul 20 '22 at 02:26
  • Btw, [don't default-export `class`es with only static methods](https://stackoverflow.com/q/29893591/1048572)! – Bergi Jul 20 '22 at 02:30

0 Answers0