JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to fix SyntaxError Cannot use import statement outside a module?

This error occurs when you use an import statement outside the JavaScript module system. Generally, you will find this error in a browser and Node.js environment.

To solve the error in the Node.js, you have to add "type": "module" to the package.json file. By adding this, you can use ES6 import and export keywords.

  "type": "module",

After adding "type": "module", you can use import and export keywords in the module.

export function sum(a, b) {
  return a + b;
import {sum} from './utils.js';

console.log(sum(3, 4)); //7

If a package.json file is not present in the project, then you add it by running npm init -y command.

$npm init -y

To solve the error in the browser, you have to add type="module" to the script element.

    <meta charset="UTF-8" />
    <script type="module">
      import { sum } from './utils.js';

      console.log(sum(3, 4));
export function sum(a, b){
  return a + b;

Recommended Posts