Syntax error cannot use import statement outside a module typescript

I have a .ts file in node js (latest version of node.js for 07.10.19) app with importing node-module without default export. I use this construction: import { Class } from 'abc'; When i run the cod...

Update: Because this answer is getting significant views I have updated it to better show the available solutions for this problem in 2022.


The error means Node found an import statement in a file that it does not consider an ECMAScript (ES) module. Adding "type": "module" to package.json will tell Node you are using ES modules, but then you will need to tell the TypeScript compiler to emit this type of module by setting "module": "es2015" or higher (for example: "es2020") in tsconfig.json . If you want to emit CommonJS modules (require), set "module": "commonjs".

In case you don’t want to set the module system at the project level, there are more fine-grained options. Files with the .mjs extension are always treated as ES modules, while files with .cjs are always treated as CommonJS modules. As of TypeScript 4.5 it is possible to use the .mts and .cts extensions as well and have the compiler emit .mjs or .cjs files, respectively.

The two systems are partially compatible. For example, it is possible to import a CommonJS module into an ES module with a default export:

// in an ES module
import thing from "./main.cjs";

The other way around. an ES module may be imported into a CommonJS module with dynamic import (ES2020 features are needed for this to work):

// in a CommonJS module
const thing = await import("./main.mjs");

Original answer (2020):

Adding "type": "module" to package.json will tell Node you are using ES2015 modules, which should get rid of the error, but then you will need to tell Typescript to generate this type of module by setting "module": "es2015" instead of "commonjs" in tsconfig.json.

This however causes a problem with the current code because although you are using an ES6 import {} statement you are exporting using the commonJS module.exports = {} syntax, and Node’s ES module loader will have an issue with it. There are two ways to deal with it:

  • Keep the module.exports but tell Node to interpret this file as commonJS by giving it a .cjs extension.
  • Change the export statement to ES2015 syntax: export function execute(…)..

The first option could get a bit tricky because the compiler will output .js files and you’d have to change it to .cjs all the time (as far as I know). With the second option you should be able to run the file with Node (including the —experimental-modules flag for versions < 13.8).

If you absolutely need to use commonJS, perhaps it is better to install the type definitions for Node: @types/node and change the import to commonJS format: require('abc') and keep the rest of the settings as they are (though you can add "type": "commonjs" to package.json to be explicit).

Cannot use import statement outside a module [React TypeScript Error Solved]

When building a web application, you may encounter the SyntaxError: Cannot use import statement outside a module error.

This error might be raised when using either JavaScript or TypeScript in the back-end. So you could be working on the client side with React, Vue, and so on, and still run into this error.

You can also encounter this error when working with JavaScript on the client side.

In this article, you’ll learn how to fix the SyntaxError: Cannot use import statement outside a module error when using TypeScript or JavaScript with Node.

You’ll also learn how to fix the error when working with JavaScript on the client side.

How to Fix the TypeScript SyntaxError: Cannot use import statement outside a module Error

In this section, we’ll work with a basic Node server using Express.

Note that if you’re using the latest version of TypeScript for your Node app, the tsconfig.json file has default rules that prevent the SyntaxError: Cannot use import statement outside a module error from being raised.

So you’re most likely not going to encounter the SyntaxError: Cannot use import statement outside a module error if you:

  • Install the latest version of TypeScript, and are using the default tsconfig.json file that is generated when you run tsc init with the latest version.
  • Setup TypeScript correctly for Node and install the necessary packages.

But let’s assume you’re not using the latest tsconfig.json file configurations.

Here’s an Express server that listens on port 3000 and logs «Hello World!» to the console:

import express from "express"

const app = express()

app.listen("3000", (): void => {
    console.log("Hello World!")
    // SyntaxError: Cannot use import statement outside a module
})

The code above looks as though it should run perfectly but the SyntaxError: Cannot use import statement outside a module is raised.

This is happening because we used the import keyword to import a module: import express from "express".

To fix this, head over to the tsconfig.json file and scroll to the modules section.

You should see a particular rule like this under the modules section:

/* Modules */
"module": "esnext" 

To fix the problem, change the value «esnext» to «commonjs».

That is:

/* Modules */
"module": "commonjs"

How to Fix the JavaScript SyntaxError: Cannot use import statement outside a module Error

Fixing the SyntaxError: Cannot use import statement outside a module error when using vanilla JS is a bit different from TypeScript.

Here’s our server:

import express from "express";

const app = express();

app.listen(3000, () => {
    console.log("Hello World!");
    // SyntaxError: Cannot use import statement outside a module
});

We’re getting the SyntaxError: Cannot use import statement outside a module error for the same reason — we used the import keyword to import a module.

To fix this, go to the package.json file and add "type": "module",. That is:

{
  "name": "js",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "type": "module",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2"
  }
}

Now you can use the import keyword without getting an error.

To fix this error when working with JavaScript on the client side (without any frameworks), simply add the attribute type="module" to the script tag of the file you want to import as a module. That is:

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

Summary

In this article, we talked about the SyntaxError: Cannot use import statement outside a module error in TypeScript and JavaScript.

This error mainly occurs when you use the import keyword to import a module in Node.js. Or when you omit the type="module" attribute in a script tag.

We saw code examples that raised the error and how to fix them when working with TypeScript and JavaScript.

Happy coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

When you try to use modules in Node.js with TypeScript for the first time, you may see the error “Cannot use import statement outside a module”. Check out the root cause and solution for it below.

Reproduce the error “Cannot use import statement outside a module”

Suppose we have this module called greeter.ts in a typical Node.js package, which prints a welcome message for visitors depending on the site name:

greeter.ts:

export function greeter(sitename: string) {
	console.log('Welcome to', sitename);
}

After exporting the function greeter(), you can import it into the main module index.ts:

index.ts:

import { greeter } from "./greeter";
greeter("LearnShareIT");

Everything looks fine, and the compiler should compile your TypeScript into JavaScript code without issues. However, when you build the project, it actually throws errors:

$ npx tsc
import { Greeter } from "./greater";
^^^^^^
SyntaxError: Cannot use import statement outside a module

You will also run into the same problem when trying to execute the index.ts file directly with node:

$ node src/index.ts
SyntaxError: Cannot use import statement outside a module

Causes and solutions

Set the module system to CommonJS

TypeScript supports modules, just like JavaScript, since the ECMAScript2015 (ES6) standard. It treats any file with a top-level export or import as a module. Meanwhile, files without them are considered scripts whose contents belong to the global scope.

To use a module (such as greeter.ts above), you need a module loader. Its job is to locate and execute all dependencies that the module needs so it can execute successfully.

The creator of JavaScript didn’t design this programming language with modules in mind from the outset. In the beginning, it was created to bring simple scripting capabilities to websites. Not until much later that modularity has been implemented into JavaScript (and therefore TypeScript).

This effort suffers from fragmentation to a certain extent. Started by a Mozilla engineer in 2009, CommonJS is a popular module system.

Node.js originally used it as the official way to package JavaScript code before it supported the ECMAScript modules standard. On top of that, there are several third-party frameworks and libraries that allow for module usage, including AMD, SystemJS, UMD, etc.

If you write your Node.js in TypeScript, you can use a syntax similar to that of ECMAScript to export or import modules. When you compile your code into JavaScript, you can set the module loader you want to target in the tsconfig.json configuration file.

It may look like this:

{
    "compilerOptions": {
        "target": "ES6",
        "lib": [
        	"ES6"
        ],
        "module": "ES2015",
        "rootDir": "src",
        "resolveJsonModule": true
    }
} 

The "module" property in this configuration sets which module code you want to output from your TypeScript project. In this example, it’s the ECMAScript standard, which is not immediately supported by Node.js. That is why you see the error “Cannot use import statement outside a module”.

You can change the module loader to CommonJS to fix this error. Edit the tsconfig.json file at the root of your project:

"module": "CommonJS",

You can now compile and execute your code without trouble:

$ npx tsc && node build/index.js
Welcome to LearnShareIT

Compile before running your code

You need to compile your TypeScript code (into JavaScript) first and execute the output instead of running it directly. Node.js is a JavaScript runtime, meaning it can parse and execute .js files outside browsers. It is meant for running .ts files.

Use tsc (or npx tsc in your Node.js project) to compile your TypeScript code:

$ npx tsc && node build/index.js
Welcome to LearnShareIT

Summary

The “Cannot use import statement outside a module” error is the result when you use node to run a .ts file directly without compiling it or when the module system of your Node.js project has been set to anything other than CommonJS. To resolve the problem, edit the tsconfig.json file and set "module" property in "compilerOptions" to "CommonJS". Finally, compile your TypeScript code before executing it.

Maybe you are interested:

  • Property ‘#’ does not exist on type ‘EventTarget’ in TS
  • Cannot invoke an object which is possibly ‘undefined’ in TS

Robert J. Charles

My name is Robert. I have a degree in information technology and two years of expertise in software development. I’ve come to offer my understanding on programming languages. I hope you find my articles interesting.


Job: Developer
Name of the university: HUST
Major: IT
Programming Languages: Java, C#, C, Javascript, R, Typescript, ReactJs, Laravel, SQL, Python

Table of Contents

Hide

  1. What is SyntaxError: cannot use import statement outside a module?
  2. How to fix SyntaxError: cannot use import statement outside a module?
    1. Solution 1 – Add “type”: “module” to package.json 
    2. Solution 2 – Add type=”module” attribute to the script tag
    3. Solution 3 – Use import and require to load the modules
  3. Configuration Issue in ORM’s
  4. Conclusion

The Uncaught SyntaxError: cannot use import statement outside a module mainly occurs when developers use the import statement on the CommonJS instead of require statement.

What is SyntaxError: cannot use import statement outside a module?

There are several reasons behind this error. First, let us look at each scenario and solution with examples.

  • If you are using an older Node version < 13
  • If you are using a browser or interface that doesn’t support ES6
  • If you have missed the type=”module” while loading the script tag
  • If you missed out on the “type”: “module” inside the package.json while working on Node projects

Many interfaces till now do not understand ES6 Javascript features. Hence we need to compile ES6 to ES5 whenever we need to use that in the project.

The other possible reason is that you are using the file that is written in the ES6 module directly inside your code. It means you are loading the src file/directory instead of referring to the dist directory, which leads to a SyntaxError.

Usually, we use a bundled or dist file that is compiled to ES5/Javascript file and then import the modules in our code.

How to fix SyntaxError: cannot use import statement outside a module?

There are 3 ways to solve this error. Let us take a look at each of these solutions.

Solution 1 – Add “type”: “module” to package.json 

If you are working on Node.js or react applications and using import statements instead of require to load the modules, then ensure your package.json has a property "type": "module" as shown below.

Adding “type”: “module” to package.json will tell Node you are using ES6 modules(es modules), which should get solve the error. 

If you would like to use the ES6 module imports in Node.js, set the type property to the module in the package.json file.

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

If you are using TypeScript, we need to edit the tsconfig.json file and change the module property to “commonjs“, as shown below.

ts.config file

Change the ts.config file as shown below to resolve the Uncaught SyntaxError: cannot use import statement outside a module error.

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

to

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

If this error mainly occurs in the TypeScript project, ensure that you are using a ts-node to transpile into Javascript before running the .ts file. Node.js can throw an error if you directly run the typescript file without transpiling.

Note: If your project does not have a package.json file, initialize it by using the npm init -y command in the root directory of your project.

Solution 2 – Add type=”module” attribute to the script tag

Another reason we get this error is if we are loading the script from the src directory instead of the built file inside the dist directory. 

It can happen if the src file is written in ES6 and not compiled into an ES5 (standard js file). The dist files usually will have the bundled and compiled files, and hence it is recommended to use the dist folder instead of src.

We can solve this error by adding a simple attribute type="module" to the script, as shown below.

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

Solution 3 – Use import and require to load the modules

In some cases, we may have to use both import and require statements to load the module properly.

For Example – 

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

Note: When using modules, if you get ReferenceError: require is not defined, you’ll need to use the import syntax instead of require.

Configuration Issue in ORM’s

Another possible issue is when you are using ORM’s such as typeORM and the configuration you have set the entities to refer to the source folder instead of the dist folder.

The src folder would be of TypeScript file and referring the entities to .ts files will lead to cannot use import statement outside a module error.

Change the ormconfig.js to refer to dist files instead of src files as shown below.

 "entities": [
      "src/db/entity/**/*.ts", // Pay attention to "src" and "ts" (this is wrong)
   ],

to

  "entities": [
      "dist/db/entity/**/*.js", // Pay attention to "dist" and "js" (this is the correct way)
   ],

Conclusion

The Uncaught SyntaxError: cannot use import statement outside a module occurs if you have forgotten to add type="module" attribute while loading the script or if you are loading the src files instead of bundled files from the dist folder.

We can resolve the issue by setting the “type”: “module” inside the package.json while working on Node projects. If we are loading the Javascript file then we need to add the attribute type="module" to the script tag.

Related Tags
  • import,
  • require,
  • SyntaxError

Sign Up for Our Newsletters

Get notified on the latest articles

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

Table of Contents
Hide
  1. How to fix cannot use import statement outside a module error?
    1. Solution 1 – Add “type”: “module” to package.json 
    2. Solution 2 – Add type=”module” attribute to the script tag
    3. Solution 3 – Use import and require to load the modules

The Uncaught syntaxerror: cannot use import statement outside a module occurs if you have forgotten to add type="module" attribute while loading the script or if you are loading the src file instead of bundled file from the dist folder.

There are several reasons behind this error, and the solution depends on how we call the module or script tag. We will look at each of the scenarios and the solution with examples.

How to fix cannot use import statement outside a module error?

Solution 1 – Add “type”: “module” to package.json 

If you are working on Node.js or react applications and using import statements instead of require to load the modules, then ensure your package.json has a property "type": "module" as shown below.

Adding “type”: “module” to package.json will tell Node you are using ES2015 modules(es modules), which should get solve the error. 

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

If you are using TypeScript, we need to edit the tsconfig.json file and change the module property to “commonjs“, as shown below.

ts.config file

Change the ts.config file as shown below to resolve the Uncaught syntaxerror: cannot use import statement outside a module error.

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

to

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

Solution 2 – Add type=”module” attribute to the script tag

Another reason we get this error is if we are loading the script from the src directory instead of the built file inside the dist directory. 

It can happen if the src file is written in es6 and not compiled into a standard js file. The dist files usually will have the bundled and compiled JavaScript file, and hence it is recommended to use the dist folder instead of src.

We can solve this error by adding a simple attribute type="module" to the script, as shown below.

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

Solution 3 – Use import and require to load the modules

In some cases, we may have to use both import and require statements to load the module properly.

For Example – 

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

Note: When using modules, if you get ReferenceError: require is not defined, you’ll need to use the import syntax instead of require.

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

Are you getting the “Cannot use import statement outside a module” error when you’re importing something?

Here’s the full error message, “Uncaught SyntaxError: Cannot use import statement outside a module”.

The main reason why you’re getting the “Uncaught ReferenceError: ms is not defined” is that modules are scoped.

Since you’re loading the library using native models, “ms” is not accessible in the script tag as it’s not in the global scope.

In other words, you’re trying to run the file independently.

According to the official Node.js documentation, import statements are only permitted in ES modules.

Hence, to fix the “Uncaught SyntaxError: Cannot use import statement outside a module” error message, you need to make Node.js treat your file as an ES module.

The error message can happen on WordPress, TypeScript, JavaScript, and more.

Before you attempt to fix it, you need to make sure that you have the latest version of Node.js.

After that, try using the methods below:

  • Method 1: Add type=”module” within the script tag
  • Method 2: Add type=”module” in the package.json file
  • Method 3: Replace “import” with “require”
  • Method 4: Reference typeORM
  • Method 5: Replace “esnext” with “commonjs”

Method 1: Add type=”module” within the script tag

Add type=”module” within the script tag.

This will denote that it is a JavaScript module.

Before (wrong):

<script src="../src/main.js"></script>

After (correct):

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

If you’re getting a CORS error from this, you need to add “Access-Control-Allow-Origin: *” in your headers.

Method 2: Add type=”module” in the package.json file

Add “type”: “module” in the nearest parent package.json file.

This will make sure that the .js and .mjs files are denoted as ES modules.

However, if you’re using .ts files, you need to use “nodemon” instead of “node”.

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

Method 3: Replace “import” with “require”

Try replacing “import { parse } from ‘node-html-parser’;” with “const parse = require(‘node-html-parser’)” or “const parse = require(‘node-html-parser’);”.

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

Method 4: Reference typeORM

You need to use “dist” and “js” instead of “src” and “ts”.

Before (wrong):

   "entities": [
      "src/db/entity/**/*.ts",
   ],

After (correct):

   "entities": [
      "dist/db/entity/**/*.js", 
   ],

Method 5: Replace “esnext” with “commonjs”

If you’re encountering the error on TypeScript, you need to do the following:

Instead of:

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

Use:

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

Conclusion

The “Uncaught SyntaxError: Cannot use import statement outside a module” error is one of the most common errors that developers face.

There are over 1.7 million views of it on StackOverflow.

In most cases, the error message happens because you didn’t include type=”module” inside the script tag.

Including type=module will denote that it is a JavaScript module.

Further reading

How to Fix “Object of Type ‘int’ has no len()”

How to Fix “python: can’t open file ‘manage.py’: [Errno 2] No such file or directory”

Best Binance Referral ID Code in 2022

The SyntaxError: Cannot Use Import Statement Outside A Module occurs when we use ES6 module syntax in a script that is not loaded as a module.

To work around the error, set the type attribute to module when loading scripts or in your package.json for Node.js apps.

How To Fix SyntaxError: Cannot Use Import Statement Outside A Module?

To fix the error, set the type attribute to module when loading the script into 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 you are able to use the ES6 module syntax in your javascript code.

index.js

import _ from 'lodash';

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

All JavaScript files that use the ES6 module syntax must be loaded with the type attribute set to module.

To use ES6 module imports in Node.js, set the type property to module in your package.json file.

package.json

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

If your project doesn’t have a package.json file, initialize it with the npm init -y command at the root of your project.

Node.js applications can now use ES6 module syntax.

index.js

import _ from 'lodash';

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

If you are importing a local file with the type attribute set to module, you must specify the .js extension.

index.js

import {sum} from './another-file.js';

console.log(sum(50, 50)); // 100

If you omit the extension, you get the “Error [ERR_MODULE_NOT_FOUND]: Cannot find Module X. “

If none of the suggestions helped, try replacing the import/export syntax with require() .

index.js

//for default exports
const myFunction = require('some-package');

//for named exports
const {someFunction} = require('some-package')

The “Cannot use import statement outside module” error also occurs if you try to run your source files that contain ES6 module import / export syntax, instead of running your compiled files from your build directory. Make sure to run your compiled files from your build/dist directory only.

If you are getting the “Cannot use import statement outside module” error in a TypeScript project, try setting module to commonjs in your tsconfig.json file.

tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "esModuleInterop": true,
    // ... your other options
  }
}

Conclusion

The SyntaxError: Cannot Use Import Statement Outside A Module occurs when we use ES6 module syntax in a script that is not loaded as a module.

To work around the error, set the type attribute to module when loading scripts or in your package.json for Node.js apps.

Recommendation

By the way if you encounter an error about importing libraries, I have here the list of articles made to solve your problem on how to fix errors in Python libraries.

  • ModuleNotFoundError: No Module Named Pycocotools
  • ERROR: Error:0308010c:Digital Envelope Routines::Unsupported
  • Only Size-1 Arrays Can Be Converted To Python Scalars
  • ModuleNotFoundError: No Module Named ‘cv2’
  • AttributeError: Module UMAP Has No Attribute UMAP
  • ModuleNotFoundError: No Module Named ‘yaml’

Inquiries

If you have any questions or suggestions about this tutorial, Please feel free to comment below.

Понравилась статья? Поделить с друзьями:
  • Syntax error cannot use import statement outside a module nodejs
  • Syntax error cannot use import statement outside a module jest
  • Syntax error cannot assign to literal
  • Syntax error cannot assign to function call
  • Syntax error cannot assign to conditional expression