How to Use ES6 Modules Import and Export Syntax in Node.js

Robin
Updated on April 4, 2023

Node.js uses the traditional "CommonJS syntax" by default. But JavaScript introduced the module syntax in its ES6 version for code splitting. It is more concise and easier to use.

In this blog post, we'll explore how to use import and export syntax from the ES6 modules in a Node.js application. If you're new to ES6 modules or are familiar with CommonJS modules but want to explore the new syntax, this is for you.

This is going to be a step-by-step guide with examples so that you can easily utilize the import and export keywords for sharing code between different JavaScript files instead of using the require() function.

To use the import and export syntax, you need to tell Node.js to treat your JavaScript file as an ES6 module. You can do this by adding "type": "module" to your package.json file. This tells Node.js to consider all .js files in your project as ES6 modules.

          {
  "name": "my-project",
  "version": "1.0.0",
  "description": "",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
        

Also Read: Best Guide on Dynamic Import in JavaScript for Importing Modules

SyntaxError: Cannot Use Import Statement Outside a Module Node.js

When you use the import statement from the ES6 module in Node.js, you will get the error "SyntaxError: Cannot use import statement outside a module", it means that Node.js is trying to interpret your code as a CommonJS module instead of an ES6 module.

This also happens if we try to export something from a JavaScript file using the export statement. It will through the error "SyntaxError: Unexpected token 'export'" if you try to run your code.

Because by default, Node.js expects us to use the module.export to export anything from a file and the require() function for importing something into a file.

Exporting with CommonJS Syntax:

          // utils.js file

const add = (a, b) => {
    return a + b
}

module.exports = {
    add,
}
        

Importing with CommonJS Syntax:

          // main.js file

const { add } = require('./utils')

const sum = add(5, 13)

console.log(sum)
        

Here, I am exporting the add() function from my utils.js file using module.exports syntax. Similarly, I am importing this function in the main.js file by calling the require() function.

This is the old way of sharing code between files. You can easily make use of the latest module syntax in your Node.js application.


How to Export in Node.js Using ES6 Module Syntax

By adding this single line "type": "module" to your package.json file, you can utilize the export keyword to export anything from your file. Now you don't have to use the CommonJS syntax in your Node.js application.

          // utils.js file

export const add = (a, b) => {
    return a + b
}
        

As you can see, I am exporting my add() function from the utils.js file using the ES6 module syntax. It won't throw the "SyntaxError: Unexpected token 'export'" error this time.

These are the exporting syntax you can use in your project.

Named Export Syntax:

          export const add = (a, b) => {
    return a + b
}
        

Default Export Syntax:

          const add = (a, b) => {
    return a + b
}

export default add


        

Also Read: Node.js Cluster: Improve Server Performance with Clustering


How to Use ES6 Module Import Syntax in Node.js

You can use the import keyword to import anything into a file without getting a syntax error. Now, you don't need to use the require() function anymore.

          // main.js file

import { add } from './utils.js'

const sum = add(5, 13)

console.log(sum)
        

Here I am using the ES6 module syntax to import the add() function for utils.js file in my main.js file. Now, if you run this code, it will work perfectly without any errors.

There are many importing syntaxes available in the JavaScript ES6 module.

Importing Default Export:

          import name from 'module-name'
        

Importing Named Export:

          import { name } from 'module-name'
        

Importing Multiple Named Export:

          import { name1, name2 } from 'module-name'
        

Importing an Entire Module:

          import * as name from 'module-name'
        

Also Read: Get Query Strings and Parameters in Express Routes on NodeJS


Conclusion

ES6 modules provide a more concise and powerful syntax for importing and exporting modules in JavaScript. you can make your code easier to read and maintain by implementing this syntax in your Node.js application.

As you can see, it is very easy to set up. You just have to add one line to your package.js file and you are good to go. Therefore, it's definitely worth exploring.

I hope from now on, you will be able to use the latest import and export syntax in Node.js instead of using the default CommonJS syntax. By leveraging the power of ES6 modules, you can write more efficient and maintainable code.

Related Posts