Cannot use import statement outside module in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 2, 2024
5 min

banner

# Table of Contents

  1. Cannot use import statement outside module in the browser
  2. Cannot use import statement outside module in Node.js
  3. Cannot use import statement outside module in TypeScript

# Cannot use import statement outside module in the browser

Depending on which browser you use, you might get a different variation of the error message:

  • in Chrome, the error is shown as: "Uncaught SyntaxError: Cannot use import statement outside a module"
  • in Firefox, the error is shown as: "Uncaught SyntaxError: import declarations may only appear at the top level of a module"

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 Node.js apps.

syntaxerror cannot use import statement outside module

To solve the error, set the type attribute to module when loading the script in your HTML code.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- โœ… set type to module โœ… --> <script type="module" src="index.js"></script> </body> </html>

set type to module in script tag

The code for this article is available on GitHub

Now you are able to use the ES6 modules syntax in your JavaScript code.

index.js
import _ from 'https://cdn.jsdelivr.net/npm/@esm-bundle/lodash@4.17.21/+esm'; console.log(_.uniq([1, 1, 3])); // ๐Ÿ‘‰๏ธ [1, 3]

All of the JavaScript files, in which you use the ES6 modules syntax, have to be loaded with the type attribute set to module.

If you get the error "Failed to resolve module specifier. Relative references must start with either" when importing in the browser, click on the link and follow the instructions.

The code for this article is available on GitHub

# Cannot use import statement outside module in Node.js

To be able to use ES6 module imports in Node.js, set the type property to module in your package.json file.

package.json
{ "type": "module", // ๐Ÿ‘‡๏ธ rest ... "dependencies": {}, "devDependencies": {}, "scripts": {} }

set type property to module in package json

If your project doesn't have a package.json file, initialize one by using the npm init -y command in the root directory of your project.

shell
npm init -y

initialize package json

Now you are able to use the ES6 modules syntax in your Node.js application.

index.js
import _ from 'lodash'; console.log(_.uniq([1, 1, 3])); // ๐Ÿ‘‰๏ธ [1, 3]

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

Here is an example of a file called another-file.js that exports a sum function.

another-file.js
// ๐Ÿ‘‡๏ธ named export export function sum(a, b) { return a + b; }

And here is how we can import the sum function into a file called index.js.

index.js
// ๐Ÿ‘‡๏ธ named import import {sum} from './another-file.js'; console.log(sum(50, 50)); // ๐Ÿ‘‰๏ธ 100

Make sure to specify the extension when importing local files.

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().

index.js
// ๐Ÿ‘‡๏ธ for default exports const myFunction = require('some-package'); // ๐Ÿ‘‡๏ธ for named exports const {someFunction} = require('some-package')

If you decide to use the require() syntax, you have to remove the line that sets the type attribute to module from your package.json file.

package.json
{ // ๐Ÿ‘‡๏ธ if you use require(), REMOVE this line "type": "module", }

Note that you can't mix and match between the import/export ES6 syntax and the CommonJS require() syntax.

Your project can only use the import/export syntax if you have the type property set to module in your package.json file.

Otherwise, you only have to use the require() syntax.

You can read more about using the ES6 import/export syntax in the following article.

# Cannot use import statement outside module in TypeScript

The error also occurs if you 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.

If you get the error in a TypeScript project, set the module option to commonjs in your tsconfig.json file.

tsconfig.json
{ "compilerOptions": { "target": "esnext", "module": "commonjs", "esModuleInterop": true, // ... your other options } }

If you get 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.

# Things to note when using the ES6 import/export syntax

When using the ES6 import/export syntax, make sure:

  • the path to the file you are importing from is correct in your import statement.
  • you have specified the extension, (e.g. .js) of the file in the import statement.
  • you haven't misspelled the name of the variable or function you're trying to import. Names of identifiers are case-sensitive in JavaScript.
  • you only have a maximum of 1 default export per file.
  • you haven't mixed up named and default exports and imports.
index.js
const num = 100; // ๐Ÿ‘‡๏ธ default export export default num; // ๐Ÿ‘‡๏ธ default import import num from './another-file.js' // ---------------------------- // ๐Ÿ‘‡๏ธ named export export const hello = 'world' // ๐Ÿ‘‡๏ธ named import import {hello} from './another-file.js'

If you got the error in a TypeScript project and this article didn't help, check out my TypeScript-specific article on how to solve the error:

If you got the error when using the JEST testing library, click on the following article:

Want to learn more about importing and exporting values in JavaScript and TypeScript? Check out these resources: Import and export Classes and Functions in JavaScript,How to Import Values from Another file in TypeScript.

# Conclusion

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 Node.js apps.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev