How To Export And Import Modules In Node.js
Node.js
29/04/2021
Importing and exporting modules in Node.js works differently than in the front-end as this functionality was created before the introduction of ECMAScript Modules.
Unless you use a compiler like Babel or ECMAScript Modules finally become a stable feature in Node.js, we are stuck with it for now. 🤷♀️
Exporting a module
The important thing to understand with Node.js modules is that you export them using JavaScript objects.
module.exports = { add: function(x, y) { return x + y }, number: 7,}In the object, you may assign your keys anything from primitives (e.g. numbers) to other objects (e.g. functions). To actually export everything, you must then assign it to module.exports.
Variations
You can write the code snippet above in different ways. Here's one:
module.exports.add = function(x, y) { return x + y} module.exports.number = 7Again, nothing unusual if you know how JavaScript objects work. You can rewrite this again in an even cleaner fashion.
function add(x, y) { return x + y} const number = 7 module.exports = { add, number }Importing a module
Once you know that you're actually importing JavaScript objects, things become quite straightforward.
const helpers = require('./helpers')In this example, we import a module (with the require function) from the helpers file, which is where defined the code from the previous section. This imported module is then assigned to a constant called helpers.
The most important thing to pay attention to is how to import local, core (Node.js) and external npm/Yarn modules.
- Local modules: Use a path in the file name (e.g.
'./helpers') - Core modules and external modules: Enter the name without a path (e.g.
'example'). Node.js will know which one you're referring to. 😉
In all cases, you don't need to specify the extension.
After importing, you can then use the content of the module.
const sum = helpers.add(helpers.number, 1)console.log(sum) // 8Destructuring the import
You can apply some good ol' destructuring to limit what you import and access the function and variable immediately.
const { add, number } = require('./helpers')
const sum = add(number, 1)console.log(sum) // 8Now that looks much cleaner, doesn't it? 😄