When importing modules, I noticed sometimes imported files have their extension, example:
import { myFunc } from './foo.js';
Whereas other libraries, the imports do not:
import { myFunc } from './foo';
Is this related to ES modules vs CommonJS modules?
It depends on your runtime and compilation environment, and also on whether you are using ES modules (the import syntax) or CommonJS modules (the require syntax). Find below an overview of the most common cases:
If the path has a file extension, then the file is bundled straightaway. Otherwise, the file extension is resolved using the resolve.extensions option, which tells the resolver which extensions are acceptable for resolution, e.g.
.js,.jsx. More on the official doc.
A file extension must be provided when using the
importkeyword to resolve relative or absolute specifiers... This behavior matches howimportbehaves in browser environments... More on the official doc.
If the exact filename is not found, then Node.js will attempt to load the required filename with the added extensions:
.js,.json, and finally.node. More on the official doc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With