Fix - Unexpected token import SyntaxError in Node.js

avatar

Borislav Hadzhiev

Tue Mar 15 20222 min read

banner

Photo by Saksham

Fix - Unexpected token import SyntaxError 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 issue.

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

package.json
{ "type": "module", // 👇️ rest ... }

If your project does not have a package.json file, you can initialize one using the npm init -y command in the root directory of your project.

Now you are able to 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);

Note that 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 you are trying to run your source files which 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.