Javaexercise.com

[Solved] Uncaught SyntaxError: Cannot Use Import Statement Outside A Module In Script

This is one of the common errors we face while loading scripts without using the "module" attribute.

In JavaScript, NodeJS, or ReactJs you may get the Uncaught syntaxerror: cannot use import statement outside a module, if you have forgotten to add type="module" attribute while loading the script into your project.

Sometimes if you load the src file instead of bundled file from the dist folder then you may get the same error.

To handle this error, we can use several approaches. Let's check this one by one with proper examples.

Fix error: cannot use import statement outside a module?

1. Adding “type”:“module” pair to package.json file

Let's start by adding the "type":"module" statement to the package.json file. You must add this line to the package.json file if you are working with any of the JS frameworks (Node.js or Reactjs).

And to include the module always prefer to use import statements instead of require statements.

See the below code for the sample, this statement basically tells to the NodeJS that you are using ES2015 modules in your project.

   {
        // ...
        "type": "module",
        // ...
    }

Solution for Typescript

If you are working with TypeScript, then edit the tsconfig.json file and update the module property to commonjs. See the sample below.

// tsconfig.json file

"target": "esnext",
"module": "esnext",

After updating the tsconfig.json fill will loop like:

"target": "esnext",
"module": "commonjs",

Fix 2 - Adding module attribute to the Script Tag

This is one of the simplest solutions to handle the error: cannot use import statement outside a module.

Here, we just need to add one attribute to the script tag and assign a module value to it. See the sample code below.

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

We usually get the error if we load the script from the src folder instead of the built file inside the dist folder of the project.

It is recommended to use the dist folder instead of src because if the src file is written in es6 and not compiled into a standard js file then the error is raised.

Fix 3 - Using import and require statements to load the modules

If the above solutions don't work then try by adding the import and require statements to load the module into your project.

Both the statements will load the module properly. 

    import { parseit } from 'node-html-parser';
    parseit = require('node-html-parser');

Note: Use the require statement only if you don't get ReferenceError: require is not defined, else use import statement.

 

For reference, you can refer: https://nodejs.org/docs/latest-v13.x/api/esm.html#esm_package_json_type_field

Upper sidebar
Sidebar bottom