(FIXED) cannot use import statement outside a module


In this article we will resolve "cannot use import statement outside a module" error in JavaScript.

In JavaScript when we use ES6 import and export statement to import a JavaScript file inside another file, we see this following error in your terminal.

Example, when we import a function from math.js inside main.js file. It throw us an error in our terminal.

main.js

import math from 'math.js'

math.add()

Terminal:

Uncaught SyntaxError: Cannot use import statement outside a module

So to resolve this error, we can try two fixes.

Use type=module in script element

To fix this error we just have to add type="module" as an attribute in the <script> element of main.js. This declare the script as a module.

<script type="module" src="main.js"></script>

The script ( in this case main.js ) into which we import the modules acts as a top-level module.

You can also embed the module script in your HTML file , just place the import module scripts in the body inside the <script> element.

<body>
  <script type="module">
    /* JavaScript module code here */
  </script>
</body>

If you don't use the type="module" , in firefox browser it will show SyntaxError: import declarations may only appear at top level of a module error.

For node.js / NPM

If you are using node application and want to use the import statement, then you will also get the "Cannot use import statement outside a module" error. It is because ES6 import and export statements are not support in node by default.

In node 9, you have to use type="module" inside your package.json file, use .mjs extension and then enable --experimental-modules flag and run:

node --experimental-modules main.js

Read full article on How to use es6 import statements in Node.js, if you are using node 12 or greater.

Troubleshoot : In node 9, if you get "ReferenceError: require is not defined" error, just use import syntax instead of require. You cannot use both import and require in your nodejs application. You have to pick one.

Related Topics:

(Resolved) npm ERR! missing script: start in Node.js application

Resolve - Node Unexpected Token Import Error

Resolve Npm Cannot Find Module Error In Nodejs

How To Fix "Npm ERR Cb() Never Called"


💾 Recommended Articles