By default, Node.js treats JavaScript code as CommonJS modules. This means that the "import
" syntax to load modules is not there. However, depending on the Node.js version you're using, you can easily tell Node.js to use ES modules, which would enable the "import
" syntax:
Enable ES Modules in Node.js v13 and Above
In Node.js v13+, you can simply add "type": "module"
to (the nearest parent) package.json
to treat .js
files as ES Modules, for example, like so:
// package.json { "name": "...", "type": "module", // ... }
After adding the "type": "module"
directive, you should be able to use import
in your code.
Please note that the "type"
field not only applies to initial entry points (e.g. node app.js
) but also to files referenced by import
statements and import()
expressions.
Enable ES Modules in Node.js v8 and Above
For Node.js v8+, if you simply change the file extension to .mjs
, Node.js will treat the code as ES modules (regardless of the type
directive in the nearest parent package.json
). This would allow you to use import
in your code.
In Node.js v8 - v12, however, you will see the following warning:
ExperimentalWarning: The ESM module loader is experimental.
To fix that, you need to additionally pass the --experimental-modules
flag when running a file, for example, like so:
node --experimental-modules app.mjs
Using the .mjs
extension provides flexibility if you wish to keep some files as CommonJS and others as ES modules. For example, this can be useful when you're migrating your code from CommonJS to ES modules.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.