Node.js is a widely used tool for executing JavaScript on the server side. A core feature of Node.js and, indeed, any programming environment, is the ability to modularize code. That is, you can write your code in several separate files for enhanced organization and readability, each of which can be imported into other files as required. This article focuses on the correct way to import a module stored in a file named example.js
in Node.js.
Two common patterns for importing modules are using require
and import
. Both ways are correct and can be employed based on your circumstances and preferences.
The traditional way to import modules in Node.js is using require()
. This function is part of the CommonJS module system that Node.js has utilized since its inception.
var example = require('./example.js');
The require('./example.js')
statement tells Node.js to look for the example.js
file in the same directory. It reads the file, executes the code it finds, and then returns the exports
object.
ES6 (ECMAScript 2015) introduced the import
statement, which enables you to import functions, objects, or values exported from an external module. Initially, import
was not natively supported in Node.js, but with the advent of ECMAScript modules in Node.js v14, you can now use it directly.
import example from './example.js';
However, be aware that to employ this syntax, it requires your Node.js environment to be in "module" mode which can be enabled by either setting the type
attribute to module
in your package.json
or by using the .mjs
extension for your file.
In conclusion, both require('./example.js')
and import example from './example.js'
are correct ways of importing a module in Node.js, although they are utilized under different circumstances. Understanding how to correctly employ them allows for more efficient code organization and enhancement of code readability in Node.js.