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
42.1k8 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
.js
files extension to.mjs
- Add
--experimental-modules
flag 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,06224 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.json
change"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,9129 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
2433 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
Hello Guys, How are you all? Hope You all Are Fine. Today When I run my index.js file and suddenly I get the following error in my stack track SyntaxError: Cannot use import statement outside a module in nodejs. So Here I am Explain to you all the possible solutions here.
Without wasting your time, Let’s start This Article to Solve This Error.
Contents
- How SyntaxError: Cannot use import statement outside a module in nodeJs Error Occurs ?
- How To Solve SyntaxError: Cannot use import statement outside a module in nodeJs Error ?
- Solution 1: Add “type”: “module” to your package.json
- Solution 2: Change module to commonjs
- Solution 3: Change .js files extension to .mjs
- Summery
When I run my index.js file and suddenly I get the following error in my stack track
SyntaxError: Cannot use import statement outside a module
Here is my Index.js file
require('dotenv').config()
import {startServer} from './server'
How To Solve SyntaxError: Cannot use import statement outside a module in nodeJs Error ?
- How To Solve SyntaxError: Cannot use import statement outside a module in nodeJs Error ?
To Solve SyntaxError: Cannot use import statement outside a module in nodeJs Error Open Your package.json file. Just 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. add “type”: “module” in the upper level as show below.
- SyntaxError: Cannot use import statement outside a module in nodeJs
To Solve SyntaxError: Cannot use import statement outside a module in nodeJs Error If you are facing issue with Typescript then just change: “module”: “esnext”, with this “module”: “commonjs”, And now your error will be solved. Thank you.
Solution 1: Add “type”: “module” to your package.json
- Open Your package.json file.
- Just 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. - add
"type": "module"
in the upper level as shown below in your package.json:
{
"name": "my-project",
"version": "0.0.0",
"type": "module",
"scripts": { ...
},
...
}
Solution 2: Change module to commonjs
If you are facing issue with Typescript then just change
"module": "esnext",
with this
"module": "commonjs",
And now your error will be solved. Thank you.
Solution 3: Change .js files extension to .mjs
- Change .js files extension to .mjs
- Add –experimental-modules flag upon running your app.
- Optional: add “type”: “module” in your package.json
- And now, your error will be solved.
Summery
It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?
Also Read
- SyntaxError: invalid syntax to repo init in the AOSP code.
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.
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 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
In this quick guide we’ll look at how you can solve the very common error, “Uncaught SyntaxError: Cannot use import statement outside a module”. This error arises when we try to use import
inside of a project which is not set up for modules — so let’s look at how you can resolve it.
Resolving the import statement outside a module error
The reason why this error occurs is because we have to explicitly tell Javascript that the file in question is a module
, in order to use the import
statement. For example, if you are using the line below, and you have not told Javascript that the file is a module, it will throw an error:
import fs from 'fs'
Depending on where you are getting the error, there are a few different ways to resolve it.
Resolving the import module error in Node.js
If you are using Node.js, this error can be resolved in two ways. The first is to update your package.json to tell Node.js that this entire project is a module. Open up your package.json, and at the top level, add "type": "module"
. For example, my package.json
will look like this:
{
// ... other package.json stuff
"type": "module"
// ... other package.json stuff
}
This will resolve the issue immediately. However, in some edge cases, you may find you have issues with this, and other parts of your code may start throwing errors. If you only want one file in your project to support import
, then change the file extension to .mjs
. For example, if your import
was in index.js
, rename index.js
to index.mjs
. Now your issue will be resolved.
Resolving the import module error in script tags
The second place this error can occur is in a script tag, like this:
<script src="mymodule.js"></script>
In this case, if mymodule.js
contains an import
statement, it won’t work. To resolve this, add type="module"
to your script tag:
<script type="module" src="mymodule.js"></script>
Now you’ll never have issues with import
again.
Last Updated 1659877729775
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.