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