Fix error

Fix – Cannot use import statement outside module in JS or TypeScript

cannot use import statement outside a module

The “Uncaught syntaxerror: Cannot use import statement outside a module” occurs in JavaScript and Typescript when you apply the ES6 Modules concept/syntax in a particular script that’s not loaded as a local or third-party module. This happens as a result of importing ECMAScript 6 that is exported as a function or a class in a different file. Also, when linking to an external JS file in HTML code, you have to specify the type attribute. In HTML, you can set the ‘type’ attribute to ‘module’ and the error will be solved <script type="module" src="index.js"></script> However, when developing a Node.js apps and you want to load a particular script, you have to do the same in your ‘package.json’ file by including ‘type’: ‘module’.

cannot use import statement outside a module

Sometimes, the error is presented as ‘Uncaught SyntaxError: import declarations may only appear at top level of a module’ instead of what is shown in the above image. You can solve this in your HTML code by setting the ‘type’ attribute to ‘module’ in the script tag. This will tell the browser that you want to use modules.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>

    <!—set type attribute to module -->
    <script type="module" src="index.js"></script>	
  </body>
</html>

Why have we set the type attribute to module in the above code? JavaScript cannot use import statement outside a module by default in ES6. Therefore, if we link to an external JS file that loads another module with the import statement, it will throw the above error if the type attribute is not set to module. But by specifying the type, you can use the ES6 modules syntax to import both local and third-party modules in your JavaScript code.

import _ from 'lodash';

// print the only the unique numbers in the array
console.log(_.uniq([1, 2, 2, 3, 3])); //Output: [1, 2, 3]

How do you fix Cannot use import statement outside a module in js? The above solution should work for you if only your project was initialized with JavaScript and not TypeScript.

In NodeJS you will experience the same error and a quick workaround is to set the ‘type’ property to ‘module’ in your ‘package.json’ file. to be able to use the ES6 module imports syntax.

{
  "type": "module",
  // rest of the object properties follows...
}

You can navigate to your project root directory from the command-line and use the command ‘npm init -y’ to initialize a ‘package.json’ file if your project does not have one. You can then go ahead and ECMAScript 6 modules syntax to import other moudles in your Node.JS application.

import _ from 'lodash';

console.log(_.uniq([4, 4, 3, 4, 1, 1, 3])); // [4,3, 1]

Remember to include the ‘.js’ extension when you import local files with the type attribute set to ‘module’ without the extension, you will encounter and error saying “Error [ERR_MODULE_NOT_FOUND]: Cannot find module X”. You also have to use an absolute path depending on where the file exists in your project directory, if not the file will fail to load.

import {subtraction} from './subtraction.js';

console.log(subtraction(100, 50)); // 👉️ 50

If the error still persist, use the ‘require()’ method to load modules instead of the ‘import/export’ syntax. But make sure not to mix them together, you can’t use both negatively, so stick to one but if you need to use both then use a bundler.

//Use this for default exports
const packageFunction = require('some-package-name');

// Use this for named exports
const { packageFunction } = require('some-package-name')

Check also, Fix error – react script command not found

Note also that if your project contains ECMAScript 6 ‘import’/’export’ module syntax and you run your compiled files from the build directory, the “Cannot use import statement outside module” error will be thrown. Instead run your whole project compiled files from the build/dist folder.

 Use the ‘.mjs’ extension if you want to use the import and export statement in your node application. Es6 does not support the import and export statement by default in node. You will get the above error if you try. You can solve it by using the .mjs extension in your project files and then you just have to run below command.

node --experimental-modules filename.mjs

If you have a TypeScript project and you encounter the “Cannot use import statement outside module” error. Inside your ‘tsconfig.json’ file you will find an object with the name ‘compilerOptions’ which has a property ‘module’ set it value to ‘commonjs’.

{
  "compilerOptions": {
    "target": "esnext",
     // change it value
    "module": "commonjs",
    "esModuleInterop": true,
    // ... your other properties follows…
  }
}

I do recommend that you don’t use ‘node’ to run your TypeScript application. A package like ‘ts-node’ will transpile and run your ‘.ts’ files in a much better way. That’s how you fix the error, Cannot use import statement outside a module in TypeScript

The “cannot use import statement outside a module” error occurs because of the following reasons:

  • It could be that you’re using an older version of NodeJS below 13.2.0
  • You did not specify that the browser should load modules in your <script> type attribute.
  • Your browser does no support ES6 modules
  • Your Node application have incorrect package.json settings.

Check also, Fix error – Object are not valid as react child

Summary

Working with modules is great, it helps you to organize your code nicely. It also saves time required to build a particular feature you need scratch. But you have to note the concept when it comes to loading both local and third-party modules. Thanks for reading and keep coding, if you have any suggestions or challenges, let me know.

Tagged

About Justice Ankomah

computer science certified technical instructor. Who is interested in sharing (Expert Advice Only)
View all posts by Justice Ankomah →

Leave a Reply

Your email address will not be published. Required fields are marked *