Table of Contents
Hide
- What is SyntaxError: cannot use import statement outside a module?
- How to fix SyntaxError: cannot use import statement outside a module?
- Solution 1 – Add “type”: “module” to package.json
- Solution 2 – Add type=”module” attribute to the script tag
- Solution 3 – Use import and require to load the modules
- Configuration Issue in ORM’s
- 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 apackage.json
file, initialize it by using thenpm 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.
Introduction
Ever started a project or followed an online tutorial and everything is going fine until you hit this error:
SyntaxError Cannot Use Import Statement Outside a Module
The error “SyntaxError Cannot Use Import Statement Outside a Module”, is caused by you trying to use a library that is written as ECMAScript modules (ESM).
Ok? So what does this mean exactly?
In JavaScript there are usually 3 ways to use external libraries:
- If you are in the browser, you can use external libraries with a
<script>
tag.
For example, using jquery library can be done as:
- Using the import statement as part ECMAScript modules. This is the more modern way of importing libraries and you will see this in more online tutorials.
Consider having a math.js file
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
Now if we want to use the math.js function, with ECMAScript modules, we can use the import
keyword:
import { add, subtract } from './math.js';
console.log(add(1, 2)); // 3
console.log(subtract(5, 3)); // 2
- Using the CommonJs require() method. This method is the more older way to managing libraries and was created before agreement on the
import
statement!
So the error message “SyntaxError Cannot Use Import Statement Outside a Module” just means that you are trying to mix and match the different ways of using a JavaScript library.
There are three ways to fix this issue:
- Update your script tag to have the
type=module
attribute - Update your package.json if your application is a Node application
- Convert
import
statements to CommonJSrequire()
equivalent - Use a transpiler like Babel to convert your import statements
1. Update your script tag to have the type=module
attribute
If you are running your JavaScript in the browser, you can change the offending library to become a module like so:
<script type="module" src="mymodule.js"></script>
You can also use it as a internal script like:
Tip: Check your file paths
Make sure that you are referencing the correct file path. As an example for relative paths, you MUST have the dot forward slash («./»)
If you import without the (‘./’) it will not work — eg this will not work:
import {a} from "module.js";
2. Update your package.json if your application is a Node application
With the latest version of Node, it uses two types of module loaders — CommonJs and ECMAScript modules. We can tell Node to use ECMAScript modules and our import statements by updating the package.json.
As an example, lets say we are trying to use the cloudinary library like import cloudinary from 'cloudinary'
.
However when running the code, we get the following error:
(node:29424) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
c:\Users\...\perspective\cloud.js:1
import cloudinary from 'cloudinary';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (node:internal/modules/cjs/loader:1018:16)
at Module._compile (node:internal/modules/cjs/loader:1066:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10)
at Module.load (node:internal/modules/cjs/loader:967:32)
at Function.Module._load (node:internal/modules/cjs/loader:807:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47
[Done] exited with code=1 in 0.183 seconds
To fix this, we need to go to our package.json file and add the type:module
setting.
(Make sure that this setting is on the top level)
{
// ... other package.json stuff
"type": "module"
// ... other package.json stuff
}
3. Convert import
statements to CommonJS require()
equivalent
A common way to fix this issue is to use only one way to load modules. Generally, you cannot mix between CommonJs and ECMAScript modules.
Just stick with one way of importing — eg either use require() from CommonJS or import keyword from ES6 modules.
As an example, lets say we are trying to use node-html-parser as a ES6 module with the import keyword:
import { parse } from 'node-html-parser';
Now this can give us the error: SyntaxError Cannot Use Import Statement Outside a Module.
To fix this, we can convert it to use CommonJS with the require() method like so:
const parse = require('node-html-parser');
Tip: Check library support for ES6 modules or CommonJS
In some cases, libraries may be only written in ES6 modules, so you cannot use the CommonJS require() method. The reverse can also occur aswell, the library is only written in CommonJS modules and therefore cannot be used with the import keyword.
In cases like this, consider changing your whole Node application to ES6 modules or wait for the author of the library to support your import method (or createa PR yourself)
4. Use a transpiler like Babel to convert your import statements
One way to make sure that all of code will be able to use ES6 Modules to to use a transpiler like Babel.
To do so we can follow the below steps:
- First we’ll install @babel/cli, @babel/core and @babel/preset-env:
npm install --save-dev @babel/cli @babel/core @babel/preset-env
- Then we’ll create a .babelrc file for configuring Babel:
touch .babelrc
This will host any options we might want to configure Babel with:
{
“presets”: [«@babel/preset-env»]
}
We then need to transpile our script first before handing over to Node to run. So on build, we pass the script to babel to transpile it for ES6 and put the code into the dist folder:
In file package.json.
"scripts": {
"build": "babel index.js -d dist"
}
Now, in our “start” commamd, we will run the code from the dist folder intead of the src. So our package.json file will look like:
"scripts": {
"build": "babel index.js -d dist", // replace index.js with your filename
"start": "npm run build && node dist/index.js"
}
Now let’s start our server:
npm start
Jest error: SyntaxError: Cannot use import statement outside a module
When you are using a testing framework like Jest, you can come across this error also:
FAIL src/configuration/notifications.test.js
● Test suite failed to run
/var/www/management/node/src/configuration/notifications.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import notifications from './notifications';
^^^^^^
SyntaxError: Cannot use import statement outside a module
The reason for this is usually due to Jest not supporting ES modules yet.
We can see our code working in Node, but not Jest when testing is due to Node supporting ESM from versions from v16+. However as of the time of writing Jest does not support ESM.
To get around this we have a few options:
-
Don’t use the esm syntax (import / export) and use CommonJs with the
require()
method -
Ensure you either disable code transforms by passing transform: {} or otherwise configure your transformer to emit ESM rather than the default CommonJS (CJS).
-
Execute node with –experimental-vm-modules, e.g. node –experimental-vm-modules node_modules/jest/bin/jest.js or NODE_OPTIONS=–experimental-vm-modules npx jest etc..
-
Consider using babel-jest in your project. (Note: newer versions of Jest should have babel-jest installed already. This applies for older projects/ versions)
Open up your terminal and install babel-jest as follows:
npm install --save-dev babel-jest
Make sure we have updated the package.json:
{
"scripts": {
"test": "jest"
},
"jest": {
"transform": {
"^.+\\.[t|j]sx?$": "babel-jest"
}
}
}
Create .babelrc
configuration file
Create a babel.config.json config in your project root and enable some presets.
To start, you can use the env preset, which enables transforms for ES2015+
npm install @babel/preset-env --save-dev
In your babel.config.json file, enable the presets like this:
{
"presets": ["@babel/preset-env"]
}
Summary
In this article, I went over step by step options to fix the error “SyntaxError Cannot Use Import Statement Outside a Module”. This error is caused by trying to use a library that is using ECMAScript modules (ESM) and we are not importing it correctly.
To fix this issue, we need to first determine where our JavaScript is running. If your JavaScript is in the browser, then update the <script>
tag to have type="module"
. If the code is in the backend with Node — update the package.json to have "type": "module"
.
The final option is to convert all import
keywords to CommonJs require()
. Transpilers such as Babel can make this quicker and be part of the build process!
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
One of the most confusing parts of the Node ecosystem is that it contains two different module systems, ESM (ECMAScript Modules) and CommonJS. This is a problem because the two module systems are incompatible with each other.
While working in Node, you might come across the following error:
SyntaxError: Cannot use import statement outside a module
In this post, we’ll learn more about the «SyntaxError: Cannot use import statement outside a module» error and how to fix it in Node.
How to fix SyntaxError: Cannot use import statement outside a module
The error «SyntaxError: Cannot use import statement outside a module» is caused by the fact that the file you’re trying to import is using the ESM module system, while the file you’re trying to import it into is using the CommonJS module system.
For example, let’s say you have a file called index.js
that uses the CommonJS module system but you try to use the import
keyword:
import { foo } from './foo.js';
This will throw the error «SyntaxError: Cannot use import statement outside a module» because the index.js
file is using the CommonJS module system.
JavaScript ESM uses the import
and export
keywords to include and make available code from other modules, respectively. CommonJS uses the require()
function to include code from other modules, and the module.exports
object to make code available to other modules.
To fix this, you will either have to continue using the CommonJS module system and use the require
keyword:
const { foo } = require('./foo.js');
Or you will have to convert your entire project to use the ESM module system and use the import
keyword:
import { foo } from './foo.js';
How to convert a CommonJS project to use the ESM module system
To convert your Node project to use the ESM module system, you will need to open your package.json
file and add the following property:
{
"type": "module"
}
By setting the type
property to module
, you are telling Node that your project uses the ESM module system.
After you do this, you will be able to use the import
keyword in your project:
import { foo } from './foo.js';
Conclusion
In this post, we learned about the «SyntaxError: Cannot use import statement outside a module» error and how to fix it in Node.
More specifically, this is caused when you try and mix the ESM and CommonJS module systems in the same project. To fix this, you will either have to continue using the CommonJS module system and use the require
keyword or switch over entirely to the ESM module system and use the import
keyword.
Thanks for reading!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
-
Support Us
-
Join
-
Share
-
Tweet
-
Share
Give feedback on this page!
Table of Contents
Hide
- How to fix cannot use import statement outside a module error?
- Solution 1 – Add “type”: “module” to package.json
- Solution 2 – Add type=”module” attribute to the script tag
- 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
.
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.