How to resolve the SyntaxError: Cannot use import statement outside a module?

About

When running a code on node.js, your code may stop with the following error:

SyntaxError: Cannot use import statement outside a module

You get this error when you try to use an import statement on Node.

Steps

Why do you get this error?

Node use the require syntax (ie commonJs Module) and does not support yet the import syntax to stitch code together.

How can you resolve this error?

To resolve this error, you have two choices:

Example with Babel

Example from Babel

yarn add @babel/preset-env --dev
{
    // To be able to use import 
    // https://babeljs.io/docs/en/babel-preset-env#targetsesmodules
    "presets": [
        [
            "@babel/preset-env",
            {
                "targets": {
                    "esmodules": true
                }
            }
        ]
    ]
}

Note on Jest

The Jest testing library should transform your module but you may still get the error for modules in the module_directory because it does not transpile any module in it by default.

Example:

node_modules\nanoid\index.prod.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { urlAlphabet } from './url-alphabet/index.js'
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    > 1 | import {customAlphabet} from "nanoid";

To resolve this error, you need to add the module in our case nanoid to be transpiled.

Example in jest.config.js where we ignore all modules in node_modules except nanoid via the transformIgnorePatterns

const config = {
    ....
    transformIgnorePatterns: ["/node_modules/(?!(nanoid)/)", "\\.pnp\\.[^\\\/]+$"],
};





Discover More
Javascript Module - Import (Es Module)

This page is the import statement defined in the es module specification The ES6 import is: a function for dynamic import (performed at runtime time) or a statement for static import (performed...



Share this page:
Follow us:
Task Runner