fix Cannot use import statement outside module in JavaScript

It seems like you’re facing an error related to the use of the import statement in JavaScript. This error occurs when you’re trying to use ECMAScript modules (ESM) syntax in a script that is not recognized as a module.

To resolve this issue, follow these steps:

  1. Make sure you’re using a modern browser or a version of Node.js that supports ECMAScript modules (for example, Node.js v12.17.0 or later).
  2. Update your HTML file to include the type="module" attribute on your script tag. This tells the browser that your script uses ESM syntax:


<!DOCTYPE html>
    <meta charset="UTF-8" />
    <title>My App</title>
    <script type="module" src="main.js"></script>
  1. In your JavaScript file, use the import statement to import the required module:


// main.js
import myFunction from './myModule.js';

  1. Ensure that the exported module uses the correct ESM syntax:


// myModule.js
export default function myFunction() {
  console.log('Hello, world!');

If you’re using Node.js, you need to specify the module type in the package.json file as well:


  "name": "my-app",
  "version": "1.0.0",
  "type": "module",
  "main": "main.js",
  "scripts": {
    "start": "node main.js"
  "dependencies": {}

By following these steps, you should be able to use the import statement without encountering the “Cannot use import statement outside module” error.


Table of Contents

Related posts