Import vs Require in Node.js
Jun 26, 2020
Node.js introduced support for the import
statement in Node.js 12, although you need to opt in by setting a package.json
configuration option.
However, Node.js has no plans to drop support for require()
(CommonJS). Which should
you use?
Below is a high-level summary of the tradeoffs:
- ESM
import
is part of the JavaScript language spec,require()
is not. import
requires a special configuration option inpackage.json
.import
does not support importing JSON files. You'll get aUnknown file extension ".json"
error if you try toimport
a file that ends in.json
.- Even though ESM modules work in both the browser and Node.js, there's no guarantee that your Node.js code will work in the browser and vice-versa.
- Several Node.js features don't work with ESM:
NODE_PATH
,__dirname
,__filename
, andrequire.extensions
don't work if you opt in to{ "type": "module" }
.
Recommendations
Even though there are numerous tradeoffs, none of the tradeoffs is sufficiently important for us to recommend using one or the other in all cases. Here's a few reasons why you might prefer one over the other:
- If you're building a full-stack application and want to use the same syntax all the way through, using ESM imports is a good choice.
- If your app uses
__dirname
for relative file paths withfs
, you need to userequire()
or refactor your app. - If you rely on importing JSON files (configuration, seed data, etc.) you need to use
require()
, or refactor your app to instead read JSON files usingfs
.
For now, Mastering JS will stick to using require()
, because that's what we're used to and we don't know of a compelling enough reason to switch.
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!