Set the Node.js Project to ECMAScript Modules (ESM)

Share this video with your friends

Social Share Links

Send Tweet

Node.js projects have two ways that you can import and export code into different files. This is through CommonJS (CJS) and ECMAScript modules (ESM).

CommonJS is Node's default way to import modules but because I like to have my Node.js code similar to my frontend code, we will use ESM for this project.

To do so we will set a project type in our package.json.

Instructor: [0:00] Node has two different ways to be able to import and export dependencies into our projects. The default is CommonJS or CJS.

[0:10] To be able to import with CommonJS, we use the require() function that's built into Node. If I wanted to get the HTTP library from Node's core, I would assign that to a variable using the require() function.

[0:24] If I want to export something from my file, I need to use the module.exports, and I can assign an object to this, which can contain any variable or function I would like to. In this case, I've got a variable of my name.

[0:38] Node developed CommonJS before JavaScript had its own module system, but in 2015, ECMAScript developed ESM modules, ECMAScript modules for ESM. The way we import from ECMAScript is we use the import keyword, we name it what we'd like, and say where we want to import it from. If I want to export a named variable, I could export a const name = Kevin.

[1:06] Because the front-end libraries use ECMAScript modules, I tend to prefer to write my Node libraries in ECMAScript as well. I'm exercising the same syntax on the backend as on the frontend. To tell Node that this package is going to run in ESM, I go to my package.json file that we've created. I may add a new line on the top level.

[1:30] The key I'm going to add is type. There are two options -- CommonJS, which is the default, or module, which is saying, "Now, I'm running an ESM." That single line now tells Node that this package's imports and exports should be managed in an ESM-styled way.