In previous artticle, I mentioned Encrypt and Decrypt string in Javascript but in this article, I have mentioned how to resolve Uncaught Error: "Cannot use import statement outside a module" using various possible methods in Javascript or NodeJS

This error, can occur when you are trying to import ES6 file in Javascript or It can also occur when you are using NodeJS.


So let's take a look at possible solutions to resolve above error.

Using Javascript Import

When you are working with ECMAScript (ES6) modules and JavaScript module import statements, you will need to add 'type=module' when importing script file, so browser can understand you are calling a module import.


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

Note: You may get CORS issue, if you are fetching file from another domain, resolve it by adding Access-Control-Allow-Origin: * in your headers.

If you are using Internal script, then also mention 'type=module' as shown below

<script type="module">
    import {a} from "./module.js";

Using NodeJs

When you are getting the error in NodeJS, you need to simply navigate to your package.json file and "type": "module".


  // package.json code here
  "type": "module",

Replace Import by Require

This can be another case, when you are getting error 'cannot use import statement outside a module' in NodeJS

// import { parse } from 'node-html-parser';
// replace above line with below
const parse = require('node-html-parser');

Usng Extension .mjs

When using ECMAScript 6 modules from a Node.js environment, use the extension .mjs in your files and you will have to use this command to run the file:

node --experimental-modules filename.mjs

Above solution work if you are using Node 12 or below, if you are using Node 14, then you can solve error by simply use above "package.json" based solution.

You may also like to read:

How to compare two arrays using Javascript and get unmacthed elements?

Read CSV file in Javascript and HTML5 FileReader (Multiple ways)

How do I remove last comma from string using jQuery or Javascript?

Read PDF file using Javascript

How to get user location using Javascript / HTML5 Geolocation?

How to check if url contains a sub-string using jQuery or javascript?

how to check if string is null or empty using jQuery or javascript?