Borislav Hadzhiev
Thu Apr 21 2022·2 min read
Photo by Surachet Khaoropwongchai
Updated - Thu Apr 21 2022
The "SyntaxError: Cannot use import statement outside a module" occurs when we
use the ES6 Modules syntax in a script that was not loaded as a module. To solve
the error, set the type
attribute to module
when loading a script or in your
package.json
for the Node apps.
To solve the error, set the type
attribute to module
when loading the script
in your HTML code.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ✅ type set to module ✅ --> <script type="module" src="index.js"></script> </body> </html>
Now we are able to use the ES6 modules syntax in our JavaScript code.
import _ from 'lodash'; console.log(_.uniq([1, 1, 3])); // 👉️ [1, 3]
Note that all of the JavaScript files you use the ES6 modules syntax in have to
be loaded with the type
attribute set to module
.
type
property to module
in your package.json
file to be able to use ES6 module imports.{ "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.
import _ from 'lodash'; console.log(_.uniq([1, 1, 3])); // 👉️ [1, 3]
Note that when you import local files and have set the type
attribute to
module
, you must include the .js
extension.
import {sum} from './another-file.js'; console.log(sum(50, 50)); // 👉️ 100
If you omit the extension, you will get an error - "Error [ERR_MODULE_NOT_FOUND]: Cannot find module X".
If none of the suggestions helped, try replacing the import/export
syntax
with require()
.
// 👇️ for default exports const myFunction = require('some-package'); // 👇️ for named exports const {someFunction} = require('some-package')
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.If you are getting the "Cannot use import statement outside module" error in a
TypeScript project, try setting module
to commonjs
in your tsconfig.json
file.
{ "compilerOptions": { "target": "esnext", "module": "commonjs", "esModuleInterop": true, // ... your other options } }
If you are getting the error in a TypeScript project, make sure to use a package
like ts-node
to transpile and run your .ts
files. The error is often caused
when you try to use node
to run a TypeScript file.
If this suggestion doesn't work in your TypeScript project, check out my TypeScript-specific article - Cannot use import statement outside a module in TypeScript.