Skip to content

Cannot Use Import Statement Outside A Module (Solved)

When this error appears it means that you are trying to use syntax that has not been brought into the module. ES6 JavaScript syntax Changing the type to module can fix it.

The Uncaught Syntax error "Cannot use import statement outside a module" is a very common error in the life of a JavaScript programmer. Javascript module import statement errors usually occur when a programmer is working on either the server-side of a javascript project or even on the client-side like the browser.

It can often be solved by setting the 'type' of the script you are trying to import to 'module'.

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

The error is usually a result of attempting to utilize the "import statement" inside of a project that is not correctly configured for the ES modules. An example would include if you import a function from another file inside the driver or the main file.

In JavaScript, a module is simply a file that contains related code. The import and export keywords are used to share and receive functionality across modules. The export keyword allows other modules to access a variable, function, class, or object.

The above error would occur in the code snippet below:

 //This is the main js file
 import math from 'math.js'
 math.subtract()

Causes of the "Cannot Use Import Statement Outside A Module" error.

This error can be thrown as a result of a number of things and the way the module or script tag is called will determine how to fix it. Below are some of the possible reasons that a programmer might encounter this error:

  1. Failure to specify a "type" when coding your browser script tag(<script>here</script>) in the html or JavaScript file.
  2. Failure to accurately and correctly configure the package.json settings when using Node.js.
  3. The use of a node version is outdated.
  4. Your browser version might not be supporting the ES modules being used.
  5. It also happens if you try to run a native source code that contains ES6 module import or export syntax instead of a compiled code from the build directory. Always make sure to only run already compiled files from the build/dist directory.

From all the above causes of the "Cannot Use Import Statement Outside A Module" error, a viable fix is available depending on how we call the module or script tag. Some of the fixes are discussed in detail in the next step of this research article.

How to solve the "Cannot Use Import Statement Outside A Module" error.

Fixing the Node.js import module error

For programmers who are using node.js, the "Cannot Use Import Statement Outside A Module" error usually occurs on the server side of a project. It may usually involve the use of a lower version of the node.js framework.

It can however be handled in two very simple ways. The first method is to inform Node.js that this entire project is a module. This can be achieved by updating the package.json file of the project.

To do this, First, open your package.json file, and secondly add the "type": "module" line of code to the top level of the file as shown in the code snippet example below.

{
    // other contents
    "type": "module",
    // other contents
}

This will immediately fix the error a lot of the time. In some projects, however, the package.json file is not automatically created. This is not a difficult issue that cannot be fixed. You will just have to create the JSON file on your own.

To create the JSON file, package.json, always run the "npm init -y" command in the root directory of the project. Having done this seamlessly, you can then go ahead to do the procedure described above and with that, your error should be fixed and your problems handled.

However, for those programmers who are using TypeScript, you will need to change the module property from "esnext" to "commonjs" in the tsconfig.json file in order to fix the error.

//The tsconfig.json file
"target": "esnext",
"module": "commonjs",

Replace the .js extension with the .mjs file extension.

In some odd instances, you might run into the "Cannot use import statement outside a module" error if you are running a node.js application and trying to utilize the "import statement".

Some portions of your native source code might start throwing errors. The reason for this is that by default, nodejs does not support ES6 import and export statements. In order to fix this problem, you will need to change the file extension from the .js extension to .mjs.

This is usually applicable if you just want only one file in your project to allow for the use of import and export statements.

Just rename the .js file extension to .mjs, for instance, if the import was in a main.js javascript file, rename it to main.mjs. Your problem will then be completely fixed.

Fixing the script tag (<script></script>) import module error

The "Cannot Use Import Statement Outside A Module" error can also occur on the client side as stated in the introductory paragraph above.

This is an instance when the error occurs in a script tag like the one shown in the html file code snippet below:

<!DOCTYPE html>
<html>
<body>
    <p id = "demo">This is a demo code spippet</p>
    <script src = "demo.js">
    </script>
</body>
</html>

If the demo.js file that has been stated as the source has any import statement in this situation, then it simply won't work. This program will throw errors. It is possible that this will occur if the src file is written in es6 and not compiled into a standard js file.

In order to fix this, you must explicitly specify that a script is a module to the browser when using ECMAScript modules and JavaScript module import and export statements. It is preferable to use the dist folder as opposed to the src folder because the dist files typically contain the packaged and compiled JavaScript file.

To accomplish this, you must add the type = "module" attribute to all the script tags pointing to JavaScript modules.

<!DOCTYPE html>
<html>
<body>
    <p id = "demo">This is a demo code spippet</p>
     <script type="module" src="demo.js">
     </script>
</body>
</html

Once you've done this, importing the module won't present any problems. Follow the routine in the script tag example above to avoid getting more errors.

Using both import and required

To properly load the module, you may be required to use both import and require statements in certain instances. The fundamental operation of require is to read a JavaScript file, run it, and then proceed to return the export object.

You must define "require" in the ES module scope before you can use it. Only two lines of code are required to complete the task as shown in the code snippet below:

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

It is however important to note that if you get an Error that states "require is not defined" when using modules, then you must use the import statement instead of the require.

Code Transpilation

Transpilers translate the native source code into another language. A transpiler allows us to write code in ES6 and have it translated into ES5 which works in almost all browsers.

It is critical that our code runs on as many different web platforms as possible. Transpilers can be a very useful tool in ensuring conformance.

Transpilers are useful for two reasons. First of all, not every new ES module is supported by every browser, and secondly, many developers use JavaScript-based programming languages like CoffeeScript or TypeScript.Babel is one of the most popular JavaScript transpilers.

Babel is a tool created to help in the translation of various JavaScript versions. It is used to convert JavaScript code from ES modules to CommonJS modules.

The node package manager can be used to install Babel (npm). To begin, launch your terminal and navigate to the folder containing your JavaScript project.

Conclusion

From the above discussion, you can clearly see that the "Cannot Use Import Statement Outside A Module" error occurs due to a failure to specify that a file is a module. This is because, in order to utilize the import statement, we must specifically tell Javascript that the file in question is a module.

With this, we can clearly understand and employ the fixes for this very common error hence reducing the instances in which our code throws this error. Before starting to troubleshoot your code, first check to see where your error originates and which of these fixes are ideal for your situation.

Comments

Latest