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.jsonfile, initialize it by using thenpm init -ycommand 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
- 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.
I’ve got an ApolloServer project that’s giving me trouble, so I thought I might update it and ran into issues when using the latest Babel. My «index.js» is:
require('dotenv').config()
import {startServer} from './server'
startServer()
And when I run it I get the error
SyntaxError: Cannot use import statement outside a module
First I tried doing things to convince TPTB* that this was a module (with no success). So I changed the «import» to a «require» and this worked.
But now I have about two dozen «imports» in other files giving me the same error.
*I’m sure the root of my problem is that I’m not even sure what’s complaining about the issue. I sort of assumed it was Babel 7 (since I’m coming from Babel 6 and I had to change the presets) but I’m not 100% sure.
Most of what I’ve found for solutions don’t seem to apply to straight Node. Like this one here:
ES6 module Import giving «Uncaught SyntaxError: Unexpected identifier»
Says it was resolved by adding «type=module» but this would typically go in the HTML, of which I have none. I’ve also tried using my project’s old presets:
"presets": ["es2015", "stage-2"],
"plugins": []
But that gets me another error: «Error: Plugin/Preset files are not allowed to export objects, only functions.»
Here are the dependencies I started with:
"dependencies": {
"@babel/polyfill": "^7.6.0",
"apollo-link-error": "^1.1.12",
"apollo-link-http": "^1.5.16",
"apollo-server": "^2.9.6",
"babel-preset-es2015": "^6.24.1",
asked Oct 14, 2019 at 21:17
11
Verify that you have the latest version of Node.js installed (or, at least 13.2.0+). Then do one of the following, as described in the documentation:
Option 1
In the nearest parent package.json file, add the top-level "type" field with a value of "module". This will ensure that all .js and .mjs files are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjs extension.
// package.json
{
"type": "module"
}
Option 2
Explicitly name files with the .mjs extension. All other files, such as .js will be interpreted as CommonJS, which is the default if type is not defined in package.json.
answered Dec 18, 2019 at 20:43
jabacchettajabacchetta
42k8 gold badges58 silver badges74 bronze badges
13
If anyone is running into this issue with TypeScript, the key to solving it for me was changing
"target": "esnext",
"module": "esnext",
to
"target": "esnext",
"module": "commonjs",
In my tsconfig.json. I was under the impression «esnext» was the «best», but that was just a mistake.
answered Jul 10, 2020 at 15:03
Dr-BracketDr-Bracket
3,8083 gold badges14 silver badges24 bronze badges
7
For those who were as confused as I was when reading the answers, in your package.json file, add
"type": "module"
in the upper level as show below:
{
"name": "my-app",
"version": "0.0.0",
"type": "module",
"scripts": { ...
},
...
}
Brian Burns
19.5k8 gold badges82 silver badges74 bronze badges
answered Jun 12, 2020 at 9:03
3
According to the official documentation:
import statements are permitted only in ES modules. For similar functionality in CommonJS, see import().
To make Node.js treat your file as an ES module, you need to (Enabling):
- add «type»: «module» to package.json
- add «—experimental-modules» flag to the Node.js call
Liam
26.7k27 gold badges120 silver badges184 bronze badges
answered Nov 21, 2019 at 14:13
7
I ran into the same issue and it’s even worse: I needed both «import» and «require»
- Some newer ES6 modules works only with import.
- Some CommonJS works with require.
Here is what worked for me:
-
Turn your js file into .mjs as suggested in other answers
-
«require» is not defined with the ES6 module, so you can define it this way:
import { createRequire } from 'module' const require = createRequire(import.meta.url);Now ‘require’ can be used in the usual way.
-
Use import for ES6 modules and require for CommonJS.
Some useful links: Node.js’s own documentation. difference between import and require. Mozilla has some nice documentation about import
answered May 22, 2020 at 4:26
us_davidus_david
4,21134 silver badges28 bronze badges
1
I had the same issue and the following has fixed it (using Node.js 12.13.1):
- Change
.jsfiles extension to.mjs - Add
--experimental-modulesflag upon running your app. - Optional: add
"type": "module"in yourpackage.json
More information: https://nodejs.org/api/esm.html
answered Nov 25, 2019 at 9:49
iseenoobiseenoob
3111 silver badge8 bronze badges
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"]
}
With recent changes to Babel, you will need to transpile your ES6 before Node.js can run it.
So, we’ll add our first script, build, in file package.json.
"scripts": {
"build": "babel index.js -d dist"
}
Then we’ll add our start script in file package.json.
"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
answered Aug 19, 2020 at 11:50
Roque OrtsRoque Orts
1901 silver badge11 bronze badges
1
I Tried with all the methods, but nothing worked.
I got one reference from GitHub.
To use TypeScript imports with Node.js, I installed the below packages.
1. npm i typescript --save-dev
2. npm i ts-node --save-dev
Won’t require type: module in package.json
For example,
{
"name": "my-app",
"version": "0.0.1",
"description": "",
"scripts": {
},
"dependencies": {
"knex": "^0.16.3",
"pg": "^7.9.0",
"ts-node": "^8.1.0",
"typescript": "^3.3.4000"
}
}
answered Nov 4, 2020 at 11:51
Rohit ParteRohit Parte
3,05224 silver badges23 bronze badges
3
Step 1
yarn add esm
or
npm i esm --save
Step 2
package.json
"scripts": {
"start": "node -r esm src/index.js",
}
Step 3
nodemon --exec npm start
answered Jul 31, 2020 at 6:22
1
Node v14.16.0
For those who’ve tried .mjs and got:
Aviator@AW:/mnt/c/Users/Adrian/Desktop/Programming/nodejs_ex$ node just_js.mjs
file:///mnt/c/Users/Adrian/Desktop/Programming/nodejs_ex/just_js.mjs:3
import fetch from "node-fetch";
^^^^^
SyntaxError: Unexpected identifier
and who’ve tried import fetch from "node-fetch";
and who’ve tried const fetch = require('node-fetch');
Aviator@AW:/mnt/c/Users/Adrian/Desktop/Programming/nodejs_ex$ node just_js.js
(node:4899) 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)
/mnt/c/Users/Adrian/Desktop/Programming/nodejs_ex/just_js.js:3
import fetch from "node-fetch";
^^^^^^
SyntaxError: Cannot use import statement outside a module
and who’ve tried "type": "module" to package.json, yet continue seeing the error,
{
"name": "test",
"version": "1.0.0",
"description": "to get fetch working",
"main": "just_js.js",
"type": "module",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "",
"license": "MIT"
}
I was able to switch to axios without a problem.
import axios from 'axios'; <— put at top of file.
Example:
axios.get('https://www.w3schools.com/xml/note.xml').then(resp => {
console.log(resp.data);
});
answered Sep 27, 2021 at 19:10
AdrianAdrian
3321 gold badge3 silver badges11 bronze badges
I found the 2020 update to the answer in this link helpful to answering this question as well as telling you WHY it does this:
Using Node.js require vs. ES6 import/export
Here’s an excerpt:
«Update 2020
Since Node v12, support for ES modules is enabled by default, but it’s still experimental at the time of writing this. Files including node modules must either end in .mjs or the nearest package.json file must contain «type»: «module». The Node documentation has a ton more information, also about interop between CommonJS and ES modules.»
answered Jul 21, 2021 at 20:41
David SDavid S
3554 silver badges6 bronze badges
5
I’m new to Node.js, and I got the same issue for the AWS Lambda function (using Node.js) while fixing it.
I found some of the differences between CommonJS and ES6 JavaScript:
ES6:
-
Add «type»:»module» in the package.json file
-
Use «import» to use from lib.
Example: import jwt_decode from jwt-decode
-
Lambda handler method code should be define like this
«exports.handler = async (event) => { }»
CommonJS:
-
Don’t add «type»:»module» in the package.json file
-
Use «require» to use from lib.
Example: const jwt_decode = require(«jwt-decode»);
-
The lambda handler method code should be defines like this:
«export const handler = async (event) => { }»
answered Aug 26, 2022 at 13:20
GowthamGowtham
4114 silver badges9 bronze badges
In my case. I think the problem is in the standard node executable. node target.ts
I replaced it with nodemon and surprisingly it worked!
The way using the standard executable (runner):
node target.ts
The way using the nodemon executable (runner):
nodemon target.ts
Do not forget to install nodemon with npm install nodemon ;P
Note: this works amazing for development. But, for runtime, you may execute node with the compiled js file!
answered Nov 29, 2020 at 8:30
LSaferLSafer
3143 silver badges7 bronze badges
1
To use import, do one of the following.
- Rename the .js file to .mjs
- In package.json file, add {type:module}
answered Feb 2, 2022 at 16:01
1
If you are using ES6 JavaScript imports:
- install
cross-env - in
package.jsonchange"test": "jest"to"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest" - more in
package.json, add these:
...,
"jest": {
"transform": {}
},
"type": "module"
Explanation:
cross-env allows to change environment variables without changing the npm command. Next, in file package.json you change your npm command to enable experimental ES6 support for Jest, and configure Jest to do it.
answered Jun 24, 2022 at 16:17
Luca C.Luca C.
11.1k1 gold badge86 silver badges77 bronze badges
This error also comes when you run the command
node filename.ts
and not
node filename.js
Simply put, with the node command we will have to run the JavaScript file (filename.js) and not the TypeScript file unless we are using a package like ts-node.
answered Sep 15, 2020 at 4:06
Jitender KumarJitender Kumar
2,3194 gold badges29 silver badges42 bronze badges
If you want to use BABEL, I have a simple solution for that!
Remember this is for nodejs example: like an expressJS server!
If you are going to use react or another framework, look in the babel documentation!
First, install (do not install unnecessary things that will only trash your project!)
npm install --save-dev @babel/core @babel/node
Just 2 WAO
then config your babel file in your repo!
file name:
babel.config.json
{
"presets": ["@babel/preset-env"]
}
if you don’t want to use the babel file, use:
Run in your console, and script.js is your entry point!
npx babel-node --presets @babel/preset-env -- script.js
the full information is here; https://babeljs.io/docs/en/babel-node
answered Dec 30, 2021 at 23:52
DanielDaniel
3332 silver badges10 bronze badges
I had this error in my NX workspace after upgrading manually. The following change in each jest.config.js fixed it:
transform: {
'^.+\.(ts|js|html)$': 'jest-preset-angular',
},
to
transform: {
'^.+\.(ts|mjs|js|html)$': 'jest-preset-angular',
},
answered Dec 30, 2021 at 13:35
PieterjanPieterjan
2,3483 gold badges22 silver badges51 bronze badges
1
I had this issue when I was running migration
Its es5 vs es6 issue
Here is how I solved it
I run
npm install @babel/register
and add
require("@babel/register")
at the top of my .sequelizerc file my
and go ahead to run my sequelize migrate.
This is applicable to other things apart from sequelize
babel does the transpiling
answered Dec 1, 2020 at 10:58
Just add --presets '@babel/preset-env'.
For example,
babel-node --trace-deprecation --presets '@babel/preset-env' ./yourscript.js
Or
in babel.config.js
module.exports = {
presets: ['@babel/preset-env'],
};
answered Jun 18, 2020 at 14:08
srghmasrghma
4,5902 gold badges34 silver badges54 bronze badges
0
To make your import work and avoid other issues, like modules not working in Node.js, just note that:
With ES6 modules you can not yet import directories. Your import should look like this:
import fs from './../node_modules/file-system/file-system.js'
answered Oct 27, 2020 at 13:59
DINA TAKLITDINA TAKLIT
5,9029 gold badges62 silver badges72 bronze badges
The documentation is confusing. I use Node.js to perform some local task in my computer.
Let’s suppose my old script was test.js. Within it, if I want to use
import something from "./mylocalECMAmodule";
it will throw an error like this:
(node:16012) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
SyntaxError: Cannot use import statement outside a module
...
This is not a module error, but a Node.js error. Forbid loading anything outside a ‘module’.
To fix this, just rename your old script test.js into test.mjs.
That’s all.
answered Sep 23, 2022 at 8:15
orfruitorfruit
1,3721 gold badge16 silver badges26 bronze badges
My solution was to include babel-node path while running nodemon as follows:
nodemon node_modules/.bin/babel-node index.js
You can add in your package.json script as:
debug: nodemon node_modules/.bin/babel-node index.js
NOTE: My entry file is index.js. Replace it with your entry file (many have app.js/server.js).
answered Feb 5, 2020 at 5:57
- I had the same problem when I started to use Babel… But later, I
had a solution… I haven’t had the problem any more so far…
Currently, Node.js v12.14.1, «@babel/node»: «^7.8.4», I use babel-node and nodemon to execute (Node.js is fine as well..) - package.json: «start»: «nodemon —exec babel-node server.js «debug»: «babel-node debug server.js»!! Note: server.js is my entry
file, and you can use yours. - launch.json. When you debug, you also need to configure your launch.json file «runtimeExecutable»:
«${workspaceRoot}/node_modules/.bin/babel-node»!! Note: plus
runtimeExecutable into the configuration. - Of course, with babel-node, you also normally need and edit another file, such as the babel.config.js/.babelrc file
answered Feb 12, 2020 at 16:48
In case you’re running nodemon for the Node.js version 12, use this command.
server.js is the «main» inside package.json file, replace it with the relevant file inside your package.json file:
nodemon --experimental-modules server.js
answered Sep 27, 2020 at 13:30
harika harika
112 bronze badges
1
I recently had the issue. The fix which worked for me was to add this to file babel.config.json in the plugins section:
["@babel/plugin-transform-modules-commonjs", {
"allowTopLevelThis": true,
"loose": true,
"lazy": true
}],
I had some imported module with // and the error «cannot use import outside a module».
answered Oct 2, 2020 at 8:43
Chalom.EChalom.E
6075 silver badges20 bronze badges
If you are using node, you should refer to this document. Just setup babel in your node app it will work and It worked for me.
npm install --save-dev @babel/cli @babel/core @babel/preset-env
answered Sep 20, 2021 at 21:37
ncutixavierncutixavier
2333 silver badges3 bronze badges
1
When I used sequelize migrations with npx sequelize db:migrate, I got this error, so my solution for this was adding the line require('@babel/register'); into the .sequelizerc file as the following image shows:
Be aware you must install Babel and Babel register.
answered Apr 20, 2022 at 18:31
DariusVDariusV
2,54314 silver badges21 bronze badges
1
Wrong MIME-Type for JavaScript Module Files
The common source of the problem is the MIME-type for «Module» type JavaScript files is not recognized as a «module» type by the server, the client, or the ECMAScript engine that process or deliver these files.
The problem is the developers of Module JavaScript files incorrectly associated Modules with a new «.mjs» (.js) extension, but then assigned it a MIME-type server type of «text/javascript». This means both .js and .mjs types are the same. In fact the new type for .js JavaScript files has also changed to «application/javascript», further confusing the issue. So Module JavaScript files are not being recognized by any of these systems, regardless of Node.js or Babel file processing systems in development.
The main problem is this new «module» subtype of JavaScript is yet known to most servers or clients (modern HTML5 browsers). In other words, they have no way to know what a Module file type truly is apart from a JavaScript type!
So, you get the response you posted, where the JavaScript engine is saying it needs to know if the file is a Module type of JavaScript file.
The only solution, for server or client, is to change your server or browser to deliver a new Mime-type that trigger ES6 support of Module files, which have an .mjs extension. Right now, the only way to do that is to either create a HTTP content-type on the server of «module» for any file with a .mjs extension and change your file extension on module JavaScript files to «.mjs», or have an HTML script tag with type="module" added to any external <script> element you use that downloads your external .js JavaScript module file.
Once you fool the browser or JavaScript engines into accepting the new Module file type, they will start doing their scripting circus tricks in the JS engines or Node.js systems you use.
answered Dec 25, 2022 at 2:06
StokelyStokely
10.6k2 gold badges31 silver badges22 bronze badges
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 initwith 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
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
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
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
There are a few different ways to use JavaScript modules but one of the most widespread approaches is EcmaScript modules, often referred to simply as ES modules. This syntax uses the import and export statements. While relatively simple to use, you may still run into errors such as the Cannot use import statements outside a module error.
The Problem
You may encounter this issue whenever you try to use an import statement.
This includes importing local modules or modules in installed packages. For example:
Code language: JavaScript (javascript)
// javascript.js import { add } from "./util.js"; // local module import date from "date-and-time"; // npm module const sum = add(1, 2); const formattedDate = date.format(new Date(), "YYYY/MM/DD"); console.log(sum); console.log(formattedDate);
If I try to run this JavaScript file using node I may receive the Cannot use import statement outside a module error despite everything in that file being correct.
The Solution
Before we continue, make sure the modules you are trying to use are setup properly. In the example above, make sure the add function is declared and exported correctly. Ensure that the date-and-time module is properly installed. With that out of the way, the solution for the error should be quite simple. You will need to add a type entry to your package.json:
Code language: JSON / JSON with Comments (json)
// package.json { // rest of your file "type": "module" }
If you do not have a package.json file but you are using node, you can create one using
npm init or yarn init depending on the package manager of your preference.
You may be importing a script into an html file in which case, instead of a package.jsonfile, you’ll need to add the type parameter to your script import:
Code language: HTML, XML (xml)
<script src="javascript.js" type="module"></script>
Conclusion
Give these solutions a try and you should no longer have to deal with that error. If not, feel free to leave a comment here and we will try our best to figure out a solution that works for you. Otherwise, have a great day and thanks for reading!




![Cannot use import statement outside a module [React TypeScript Error Solved]](https://www.freecodecamp.org/news/content/images/size/w2000/2022/11/markus-spiske-iar-afB0QQw-unsplash.jpg)

