How to solve - cannot use import statement outside a module

Published on

When you see the error message Uncaught SyntaxError: cannot use import statement outside a module, it means you're using an import statement outside of an ES Module.

There are a number of ways to solve this:

1. Transpile your code

You can use a transpiler such as Babel. This will transform your JavaScript code from ES modules to CommonJS. Typically, when transpiling your code, you would also use a bundler such as Webpack or Rollup, as these give you some added benefits such as tree shaking.

2. Set "type" to "module" in package.json

If your project is Node based, you can open your package.json file and set the type property to module. This will tell Node that you are using ES modules.

{
"type": "module"
}

You will also need to make sure you're using Node version 12 or higher as this was the first Node version to include ES module support. You can check your Node version by running the following command: node -v.

3. Set "type" to "module" in script tag

If your project is browser based, then set the type property to module on the script tag. This will tell the browser to treat the JavaScript file as an ES module.

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

The above solutions will fix this error in the majority of cases. If you're using RunJS and you see this error, then you can solve this by opening the preferences window, going to the transpilation tab Preferences > Transpilation and ticking the option labelled Enable transpilation with Babel .

runjs transpilation

Join the RunJS mailing list