SyntaxError: Unexpected token import in Node.js

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

SyntaxError: Unexpected token import in Node.js #

The "SyntaxError: Unexpected token import" occurs when we use the ES6 import syntax in a version of Node that doesn't support it. To solve the error, use the require syntax, e.g. const myPackage = require('my-package') or set the type attribute to module in your package.json file.

Here is an example of how the error occurs.

index.js
import {sum} from './another-file'; import somePackage from 'some-package' /** * import {sum} from './another-file'; ^^^^^^ SyntaxError: Cannot use import statement outside a module */

To solve the error, replace your ES6 modules import with a require import that is supported in your version of Node.js.

index.js
// 👇️ named import for local file (relative path) const {sum} = require('./another-file'); // 👇️ default import for 3rd party package (absolute path) const somePackage = require('some-package');

Using the require CommonJS modules syntax will solve the error.

If you prefer to use the ES6 modules syntax, set the type attribute to module in your package.json file.

package.json
{ "type": "module", // 👇️ rest ... }
If you don't have a package.json file, initialize one using the npm init -y command in the root directory of your project.

Now you can use ES6 modules syntax in your Node.js application.

index.js
import _ from 'lodash'; import express from 'express'; // 👇️ import from local file (INCLUDE EXTENSION!!!) import {sum} from './another-file.js'; console.log(_.uniq([1, 1, 3])); // 👉️ [1, 3] console.log(sum(10, 10)); // 👉️ 20 console.log(express);

When you import local files and have set the type attribute to module, you must include the .js extension.

index.js
import {sum} from './another-file.js'; console.log(sum(25, 25)); // 👉️ 50

If you omit the extension, you will get an error - "Error [ERR_MODULE_NOT_FOUND]: Cannot find module X".

The "SyntaxError: Unexpected token import" also occurs if try to run your source files that contain ES6 module import / export syntax, instead of running your compiled files from your build directory.

Make sure to run your compiled files from your build/dist directory only.

Conclusion #

The "SyntaxError: Unexpected token import" occurs when we use the ES6 import syntax in a version of Node that doesn't support it. To solve the error, use the require syntax, e.g. const myPackage = require('my-package') or set the type attribute to module in your package.json file.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.