Ads by ProfitSence
Close

SyntaxError - Cannot use import statement outside a module

Last Updated on Wednesday 5th Oct 2022

syntaxerror: cannot use import statement outside a module

The SyntaxError: Cannot use import statement outside a module happens when the ES6 Modals syntax is used in a script which was not loaded as a Module.

You can fix the problem by setting the type attribute of a module to load a script, or in your package.json for Node apps.

You can fix the problem by setting the type attribute to module while loading the script into your HTML code.

			
					<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>My Website</title>
    <link rel="stylesheet" href="./style.css">
    <link rel="icon" href="./favicon.ico" type="image/x-icon">
  </head>
  <body>
    <main>
        <h1>Welcome to My Website</h1>  
    </main>

    <!-- type set to module  -->
    <script src="index.js" type="module"></script>
  </body>
</html>

			
	

We can now use the ES6 module syntax in our JavaScript code.

uncaught syntaxerror: cannot use import statement outside a module

			
					import _ from 'underscore';

console.log(_.lastIndexOf([1, 2, 3, 1, 2, 3], 2)); // 👉️ 4

			
	

All JavaScript files that use the ES6 module syntax must be loaded with the type attribute set to module.

cannot use import statement outside a module

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

			
					{
  "description": "New Kit",
  "type": "module",
  // ...
}

			
	

If you don't have a package.json file in your project, you can create one by using the init command located in your root directory.

			
					npm init -y

			
	

You can now use ES6 module syntax in your Node.js app.

			
					import _ from 'underscore';

console.log(_.lastIndexOf([1, 2, 3, 1, 2, 3], 2)); // 👉️ 4