How to Fix “Cannot Use Import Statement Outside a Module” in Javascript?

javascript

The error "Cannot use import statement outside a module" occurs when you try to use an import statement in a JS file that is not a module. To fix this error, you need to ensure that your file is a module.

There are two ways to make your JS file a module:

  1. Use the ES6 module syntax by adding "type='module'" to the script tag in your HTML file. Example:

<script type="module" src="path/to/your/script.js"></script>

In your JS file, use import/export syntax to import and export modules. Example:

// in your modules.js file
export function sum(a, b) {
  return a + b;
}

// in your main.js file
import { sum } from './modules.js';
console.log(sum(1, 2)); // 3
  1. Use Node.js CommonJS module syntax by using the require() method to import modules and module.exports to export modules.

In your JS file, use require() to import modules and module.exports to export modules. Example:

// in your modules.js file
module.exports = {
  sum: function(a, b) {
    return a + b;
  }
}

// in your main.js file
const { sum } = require('./modules.js');
console.log(sum(1, 2)); // 3

Note that ES6 module syntax is supported in modern browsers, while CommonJS module syntax is used in Node.js environment.

Latest Questions

javascript How to Check if a Javascript Array Includes a Given Value? javascript How to Completely Uninstall Nodejs, and Reinstall From Scratch on Mac OS X? javascript How to Map Values of a Javascript Object to a New Object Using a Function?