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
importis part of the JavaScript language spec,require()is not. importrequires a special configuration option inpackage.json.importdoes not support importing JSON files. You'll get aUnknown file extension ".json"error if you try toimporta 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.extensionsdon'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
__dirnamefor 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!
More Node Tutorials
- Getting Started with Oso Authorization in Node.js
- Check if a File Exists in Node.js
- How To Fix "__dirname is not defined" Error in Node.js
- Working with UUID in Node
- Using bcrypt-js to Hash Passwords in JavaScript
- Working with the Node.js assert Library
- Modify Authorized redirect_uris For Google OAuth