Fix - Cannot use import statement outside module in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Fix - Cannot use import statement outside module #

The "SyntaxError: Cannot use import statement outside a module" occurs when we use the ES6 Modules syntax in a script that was not loaded as a module. To solve the error, set the type attribute to module when loading the script - <script type="module" src="index.js"></script>.

syntaxerror cannot use import statement outside module

Here's an example of how the error occurs. This is our index.html file.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ๐Ÿ‘‡๏ธ Loading script without type="module" --> <script src="index.js"></script> </body> </html>

And here's our JavaScript file - index.js.

index.js
// โ›”๏ธ Uncaught SyntaxError: // Cannot use import statement outside a module import _ from 'lodash'; console.log(_.uniq([1, 1, 3]));

We're using the ES6 Modules syntax, however we haven't set the type attribute to `module when loading the script.

To solve the "Cannot use import statement outside a module" error, set the type attribute to module when loading the script in your HTML code.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- โœ… type set to module โœ… --> <script type="module" src="index.js"></script> </body> </html>

Now we are able to use the ES6 modules syntax in our JavaScript code.

index.js
import _ from 'lodash'; console.log(_.uniq([1, 1, 3])); // ๐Ÿ‘‰๏ธ [1, 3]

Note that all of the JavaScript files you use the ES6 modules syntax in have to be loaded with the type attribute set to module.

When working with Node.js, you have to set the type property to module in your package.json file to be able to use ES6 module imports.
package.json
{ "type": "module", // ๐Ÿ‘‡๏ธ rest ... }

If your project does not have a package.json file, you can initialize one using the npm init -y command in the root directory of your project.

Now you are able to use ES6 modules syntax in your Node.js application.

index.js
import _ from 'lodash'; console.log(_.uniq([1, 1, 3])); // ๐Ÿ‘‰๏ธ [1, 3]

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee