Меню

Cannot use import statement outside a module ошибка js

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",

Peter Mortensen's user avatar

asked Oct 14, 2019 at 21:17

user3810626's user avatar

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.

Peter Mortensen's user avatar

answered Dec 18, 2019 at 20:43

jabacchetta's user avatar

jabacchettajabacchetta

41.7k8 gold badges58 silver badges73 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.

Peter Mortensen's user avatar

answered Jul 10, 2020 at 15:03

Dr-Bracket's user avatar

Dr-BracketDr-Bracket

3,7502 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's user avatar

Brian Burns

19.4k8 gold badges82 silver badges73 bronze badges

answered Jun 12, 2020 at 9:03

L. Theodore Obonye's user avatar

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's user avatar

Liam

26.7k27 gold badges120 silver badges183 bronze badges

answered Nov 21, 2019 at 14:13

Konstantin Gatilin's user avatar

7

I ran into the same issue and it’s even worse: I needed both «import» and «require»

  1. Some newer ES6 modules works only with import.
  2. Some CommonJS works with require.

Here is what worked for me:

  1. Turn your js file into .mjs as suggested in other answers

  2. «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.

  3. 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

Peter Mortensen's user avatar

answered May 22, 2020 at 4:26

us_david's user avatar

us_davidus_david

4,20134 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 your package.json

More information: https://nodejs.org/api/esm.html

Peter Mortensen's user avatar

answered Nov 25, 2019 at 9:49

iseenoob's user avatar

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

Peter Mortensen's user avatar

answered Aug 19, 2020 at 11:50

Roque Orts's user avatar

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"
  }
}

Alisson Reinaldo Silva's user avatar

answered Nov 4, 2020 at 11:51

Rohit Parte's user avatar

Rohit ParteRohit Parte

3,05424 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

Abhishek Kumar's user avatar

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

Adrian's user avatar

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 S's user avatar

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) => { }»

Peter Mortensen's user avatar

answered Aug 26, 2022 at 13:20

Gowtham's user avatar

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!

Peter Mortensen's user avatar

answered Nov 29, 2020 at 8:30

LSafer's user avatar

LSaferLSafer

3143 silver badges7 bronze badges

1

To use import, do one of the following.

  1. Rename the .js file to .mjs
  2. In package.json file, add {type:module}

answered Feb 2, 2022 at 16:01

Vidya Sagar H J's user avatar

1

If you are using ES6 JavaScript imports:

  1. install cross-env
  2. in package.json change "test": "jest" to "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest"
  3. 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.

Peter Mortensen's user avatar

answered Jun 24, 2022 at 16:17

Luca C.'s user avatar

Luca C.Luca C.

11k1 gold badge84 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.

Peter Mortensen's user avatar

answered Sep 15, 2020 at 4:06

Jitender Kumar's user avatar

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!

example for express server node js and babel

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

example babel without file

the full information is here; https://babeljs.io/docs/en/babel-node

answered Dec 30, 2021 at 23:52

Daniel's user avatar

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

Pieterjan's user avatar

PieterjanPieterjan

2,3522 gold badges22 silver badges50 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

Ahmed Adewale's user avatar

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'],
};

Peter Mortensen's user avatar

answered Jun 18, 2020 at 14:08

srghma's user avatar

srghmasrghma

4,5802 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'

Peter Mortensen's user avatar

answered Oct 27, 2020 at 13:59

DINA TAKLIT's user avatar

DINA TAKLITDINA TAKLIT

5,8629 gold badges61 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.

Peter Mortensen's user avatar

answered Sep 23, 2022 at 8:15

orfruit's user avatar

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).

Peter Mortensen's user avatar

answered Feb 5, 2020 at 5:57

ishab acharya's user avatar

  1. 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..)
  2. 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.
  3. 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.
  4. Of course, with babel-node, you also normally need and edit another file, such as the babel.config.js/.babelrc file

Peter Mortensen's user avatar

answered Feb 12, 2020 at 16:48

MrLetmein's user avatar

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

Peter Mortensen's user avatar

answered Sep 27, 2020 at 13:30

harika 's user avatar

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».

Peter Mortensen's user avatar

answered Oct 2, 2020 at 8:43

Chalom.E's user avatar

Chalom.EChalom.E

5594 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

ncutixavier's user avatar

ncutixavierncutixavier

2233 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:

Enter image description here

Be aware you must install Babel and Babel register.

Peter Mortensen's user avatar

answered Apr 20, 2022 at 18:31

DariusV's user avatar

DariusVDariusV

2,52314 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

Stokely's user avatar

StokelyStokely

10.2k1 gold badge31 silver badges22 bronze badges

Earlier today I was working on a small-ish project. I had a couple files to start with, a main.js file and another one, we’ll call it foo.js. I thought, since I have done this a million times before, that I could just import { whatever } from './foo.js'; and it would work like it always does. Problem is, I forgot one major piece of the puzzle. Let’s see what that missing piece was.

The Javascript error “SyntaxError: Cannot use import statement outside a module” occurs when using import in some Javascript code that’s not considered a module. Fix it by adding "type": "module" to your package.json file, or adding type="module" to your <script> tags.

❌ Problem: You don’t have a package.json

The most common cause of this error is that you don’t have a package.json, or it’s missing the "type": "module" property. Not to worry! This is a super simple fix. Let’s recreate the problem so you can see what causes it.

First, let’s take a look at (a simplified version of) the file structure I was working with. Here’s the files that were in my working directory when I got this error message:

./
├── foo.js
└── main.js

That’s it, just two files. Again, these aren’t the exact files I was working with. I simplified the situation so it would be easier to explain. Here’s what’s in the example main.js:

import { foo } from './foo.js';

console.log(foo);

Pretty simple, right? We’re just importing a variable called foo from foo.js and printing out the contents of that variable to the console. Let’s now take a look at what’s actually in foo.js:

export const foo = "bar";

That’s it, just one line. A variable called foo that is exported, with a value of "bar". Can’t get much simpler than that!

But these two simple files caused me some problems when I ran main.js with the following command:

After running that, the error I got was:

(node:547896) 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)
/home/user/main.js:1
import { foo } from './foo';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1032:15)
    at Module._compile (node:internal/modules/cjs/loader:1067:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

Woof! that’s a nasty looking error message for what ended up being a pretty simple fix. If you look up at the top line of the error message, it tells you exactly what you need to do. So… on to the first solution!

✅ Fix: Create package.json and set the type property to "module"

For this situation, which is the simplest, all we need to do is create a package.json file. This file is what Node uses to determine some key things about the code it’s running. All it has to do is exist in the directory you’re running the node command from; you don’t have to specify its location on the command line or anything like that.

Here’s the bare minimum you’d need to have in package.json to prevent “SyntaxError: Cannot use import statement outside a module”:

That’s it! That’s all there is to it in this case. However, there are other situations where you may have this error happen – read on to find out!

❌ Problem: You’re using import in a <script> tag

Let’s say, instead of running some Javascript files on your server (or local machine) with Node, you’re actually using import within a webpage’s <script> tag. This is possible to do, unlike it was a few years ago, but you have to do it right!

Let’s take a look at some code that will cause the error.

First, this is the directory structure of our example:

./
├── foo.js
└── index.html

What we have is two files; the foo.js file is the Javascript that has some exports in it that we want to import into a <script> tag in index.html. Make sense? Good.

Here’s what we have in our index.html file:

<!doctype html>
<html>
    <head>
        <title>My cool webpage!</title>
    </head>
    <body>
        <h2>Here's some content</h2>
        <p>Blah blah blah blah blah blah</p>
        <script src="foo.js"></script>
        <script>
            import { foo } from './foo.js';
            console.log(foo);
        </script>
    </body>
</html>

Looks pretty simple. Of course, if you were reading this 5 years ago, you’d say “wait, no way! import and export are just Webpack things, aren’t they?”. And you’d have been right. But, the ES standards have come a long way, and we’re living in the future now, so we can do this (in most browsers).

Below is what we have in our foo.js file:

export const foo = "bar";

Just like our previous example, all we are doing in foo.js is exporting a variable foo with the value of "bar".

Now, in order to run this example, we have to have a web server. Before you go spinning up a full-blown Nginx instance somewhere, chillax. We have a much simpler solution at our fingertips: Python 3’s http.server module. It’s great for situations like this.

All we have to do is run the following command and we’ll serve up this folder via HTTP:

And then we’ll see some output like this, letting us know that it’s waiting for requests:

Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...

Cool! Now let’s browse to the page and see what happens (open up the dev console!):

Whoops, looks like we’ve got two errors now! Well, better not waste any more time. Let’s get to fixing this.

✅ Fix: Set the type property of your <script> tags to “module”

Just like with our Node example above, what we have to do here is let the Javascript interpreter know that we are indeed acting like an ES6 module here. That way, the import and export statements will be recognized as valid.

Here’s the correct version of index.html:

<!doctype html>
<html>
    <head>
        <title>My cool webpage!</title>
    </head>
    <body>
        <h1>Here's some content</h1>
        <p>Blah blah blah blah blah blah</p>
        <script src="foo.js" type="module"></script>
        <script type="module">
            import { foo } from './foo.js';
            console.log(foo);
        </script>
    </body>
</html>

Note the type="module" properties added to both the imported foo.js script tag, and the inline script tag that we have our import statement in.

Now, when we reload the webpage, we should see the expected output in the dev tools console:

Success!

I’ll be honest, the fact that this worked at all surprised me too. I’m not typically using import or export right there in the raw HTML file. In fact, I’m usually building React applications – but that’s a discussion for another day.

Speaking of React applications…

❌ Problem: You included the unpacked Javascript in a Webpack based project

We’ll just quickly go over this last probable cause of the “SyntaxError: Cannot use import statement outside a module” error, since it’s so simple.

Situation: you’re working on a React app (or something else that’s packed with Webpack). Your app builds correctly, you have the Javascript included in your index.html page, you think you’re good to go. But then you get this dreaded error when you go look at the page’s dev console.

What happened?

✅ Fix: Include the bundle.json in your HTML file instead

You probably accidentally imported the un-webpacked Javascript code in your index.html file. Typically, this will be found in a directory called src. The packed Javascript file will probably be located in a directory called dist and be called something like bundle.json.

Since every project structure is different, you’re kind of on your own here for finding the bundled Javascript. But, if you look around, I’m sure you’ll find it. If not, yell at your project lead. But don’t tell them I told you to do that 😉

Conclusion

In this article, we looked at a three different causes of the Javascript error “SyntaxError: Cannot use import statement outside a module”. The bottom line is, you have to use import and export in a module, not just plain old Javascript.

To summarize, here’s three things you should check and try:

  • If you’re using Node on the back end, make sure you have a package.json file and it has "type": "module" as one of its properties
  • If you’re having this error with embedded Javascript in <script> tags, make sure both your embedded script and the one you’re importing have the property type="module".
  • If you’re using Webpack, make sure the script you include in your HTML file is the bundled Javascript and not the raw stuff in the src directory.

That’s all for now, hope it helps!

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

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

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

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

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

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

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

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

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

ts.config file

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

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

to

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

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

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

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

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

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

Solution 3 – Use import and require to load the modules

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

For Example – 

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

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

Avatar Of Srinivas Ramakrishna

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

Sign Up for Our Newsletters

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import express from "express"

const app = express()

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

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

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

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

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

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

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

That is:

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

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

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

Here’s our server:

import express from "express";

const app = express();

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

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

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

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

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

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

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

Summary

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

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

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

Happy coding!



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

JavaScript programs started small by being used here and there. Over time, the usage of JavaScript increased and we’re writing full applications that run in the browser. These large applications can be hard to maintain. It makes sense to think about ways of splitting them up into modules.

Modern browsers ship with native module support allowing them to optimize which module must be loaded.

A common error with modules is the “Uncaught SyntaxError: Cannot use import statement outside a module”. This error means you must explicitly tell the environment that the loaded file is a module. Let’s have a look at how to do that in the browser and Node.js

Node.js Series Overview

  • Node.js
  • Strings
  • Streams
  • Date & Time
  • Arrays
  • Promises
  • JSON
  • Iterators
  • Classes
  • Numbers
  • Objects
  • File System
  • Map
  • Process
  • Symbols
  • Platform/OS
  • HTTPS
  • Hashing
  1. Increase the Memory Limit for Your Process

  2. Why You Should Add “node” in Your Travis Config

  3. Create a PDF from HTML with Puppeteer and Handlebars

  4. Create Your Own Custom Error

  5. Retrieve a Request’s IP Address in Node.js

  6. Detect the Node.js Version in a Running Process or App

  7. How to Base64 Encode/Decode a Value in Node.js

  8. Check if a Value Is Null or Undefined in JavaScript or Node.js

  9. How to Fix “Uncaught SyntaxError: Cannot use import statement outside a module”

  10. Fix „Socket Hang Up“ Errors

  11. Nested Destructuring in JavaScript or Node.js


  1. Increase the Memory Limit for Your Process


  2. Why You Should Add “node” in Your Travis Config

  3. Create a PDF from HTML with Puppeteer and Handlebars

  4. Create Your Own Custom Error

  5. Retrieve a Request’s IP Address in Node.js

  6. Detect the Node.js Version in a Running Process or App

  7. How to Base64 Encode/Decode a Value in Node.js

  8. Check if a Value Is Null or Undefined in JavaScript or Node.js

  9. How to Fix “Uncaught SyntaxError: Cannot use import statement outside a module”
  10. Fix „Socket Hang Up“ Errors

  11. Nested Destructuring in JavaScript or Node.js

  1. String Replace All Appearances

  2. Remove All Whitespace From a String in JavaScript

  3. Generate a Random ID or String in Node.js or JavaScript

  4. Remove Extra Spaces From a String in JavaScript or Node.js

  5. Remove Numbers From a String in JavaScript or Node.js

  6. Get the Part Before a Character in a String in JavaScript or Node.js

  7. Get the Part After a Character in a String in JavaScript or Node.js

  8. How to Check if a Value is a String in JavaScript or Node.js

  9. Check If a String Includes All Strings in JavaScript/Node.js/TypeScript

  10. Check if a Value is a String in JavaScript and Node.js

  11. Limit and Truncate a String to a Given Length in JavaScript and Node.js

  12. Split a String into a List of Characters in JavaScript and Node.js

  13. How to Generage a UUID in Node.js

  14. Reverse a String in JavaScript or Node.js

  15. Split a String into a List of Lines in JavaScript or Node.js

  16. Split a String into a List of Words in JavaScript or Node.js

  17. Detect if a String is in camelCase Format in Javascript or Node.js

  18. Check If a String Is in Lowercase in JavaScript or Node.js

  19. Check If a String is in Uppercase in JavaScript or Node.js

  20. Get the Part After First Occurrence in a String in JavaScript or Node.js

  21. Get the Part Before First Occurrence in a String in JavaScript or Node.js

  22. Get the Part Before Last Occurrence in a String in JavaScript or Node.js

  23. Get the Part After Last Occurrence in a String in JavaScript or Node.js

  24. How to Count Words in a File

  25. How to Shuffle the Characters of a String in JavaScript or Node.js

  26. Append Characters or Words to a String in JavaScript or Node.js


    (Coming soon)

  27. Check if a String is Empty in JavaScript or Node.js


    (Coming soon)

  28. Ensure a String Ends with a Given Character in JavaScript or Node.js


    (Coming soon)

  29. Left-Trim Characters Off a String in JavaScript or Node.js


    (Coming soon)

  30. Right-Trim Characters Off a String in JavaScript or Node.js


    (Coming soon)

  31. Lowercase the First Character of a String in JavaScript or Node.js


    (Coming soon)

  32. Uppercase the First Character of a String in JavaScript or Node.js


    (Coming soon)

  33. Prepend Characters or Words to a String in JavaScript or Node.js


    (Coming soon)

  1. String Replace All Appearances

  2. Remove All Whitespace From a String in JavaScript

  3. Generate a Random ID or String in Node.js or JavaScript

  4. Remove Extra Spaces From a String in JavaScript or Node.js

  5. Remove Numbers From a String in JavaScript or Node.js

  6. Get the Part Before a Character in a String in JavaScript or Node.js

  7. Get the Part After a Character in a String in JavaScript or Node.js

  8. How to Check if a Value is a String in JavaScript or Node.js

  9. Check If a String Includes All Strings in JavaScript/Node.js/TypeScript

  10. Check if a Value is a String in JavaScript and Node.js

  11. Limit and Truncate a String to a Given Length in JavaScript and Node.js

  12. Split a String into a List of Characters in JavaScript and Node.js

  13. How to Generage a UUID in Node.js

  14. Reverse a String in JavaScript or Node.js

  15. Split a String into a List of Lines in JavaScript or Node.js

  16. Split a String into a List of Words in JavaScript or Node.js

  17. Detect if a String is in camelCase Format in Javascript or Node.js

  18. Check If a String Is in Lowercase in JavaScript or Node.js

  19. Check If a String is in Uppercase in JavaScript or Node.js

  20. Get the Part After First Occurrence in a String in JavaScript or Node.js

  21. Get the Part Before First Occurrence in a String in JavaScript or Node.js

  22. Get the Part Before Last Occurrence in a String in JavaScript or Node.js

  23. Get the Part After Last Occurrence in a String in JavaScript or Node.js

  24. How to Count Words in a File

  25. How to Shuffle the Characters of a String in JavaScript or Node.js

  26. Append Characters or Words to a String in JavaScript or Node.js

    (Coming soon)
  27. Check if a String is Empty in JavaScript or Node.js

    (Coming soon)
  28. Ensure a String Ends with a Given Character in JavaScript or Node.js

    (Coming soon)
  29. Left-Trim Characters Off a String in JavaScript or Node.js

    (Coming soon)
  30. Right-Trim Characters Off a String in JavaScript or Node.js

    (Coming soon)
  31. Lowercase the First Character of a String in JavaScript or Node.js

    (Coming soon)
  32. Uppercase the First Character of a String in JavaScript or Node.js

    (Coming soon)
  33. Prepend Characters or Words to a String in JavaScript or Node.js

    (Coming soon)

  1. Filter Data in Streams

  1. Get Number of Seconds Since Epoch in JavaScript

  2. Get Tomorrow’s Date in JavaScript

  3. Increase a Date in JavaScript by One Week

  4. Add Seconds to a Date in Node.js and JavaScript

  5. Add Month(s) to a Date in JavaScript or Node.js

  6. Add Week(s) to a Date in JavaScript or Node.js

  7. Get the Current Year in JavaScript or Node.js

  8. How to Get a UNIX Timestamp in JavaScript or Node.js

  9. How to Convert a UNIX Timestamp to a Date in JavaScript or Node.js

  10. Add Days to a Date in JavaScript or Node.js

  11. Get Yesterday’s Date in JavaScript or Node.js

  12. Add Minutes to a Date in JavaScript or Node.js


    (Coming soon)

  13. Add Hours to a Date in JavaScript or Node.js


    (Coming soon)

  14. Check If a Date Is Today in JavaScript or Node.js

  15. Check If a Date is Tomorrow in JavaScript or Node.js

  16. Check If a Date is Yesterday in JavaScript or Node.js

  17. How to Format a Date YYYY-MM-DD in JavaScript or Node.js

  1. Get Number of Seconds Since Epoch in JavaScript

  2. Get Tomorrow’s Date in JavaScript

  3. Increase a Date in JavaScript by One Week

  4. Add Seconds to a Date in Node.js and JavaScript

  5. Add Month(s) to a Date in JavaScript or Node.js

  6. Add Week(s) to a Date in JavaScript or Node.js

  7. Get the Current Year in JavaScript or Node.js

  8. How to Get a UNIX Timestamp in JavaScript or Node.js

  9. How to Convert a UNIX Timestamp to a Date in JavaScript or Node.js

  10. Add Days to a Date in JavaScript or Node.js

  11. Get Yesterday’s Date in JavaScript or Node.js

  12. Add Minutes to a Date in JavaScript or Node.js

    (Coming soon)
  13. Add Hours to a Date in JavaScript or Node.js

    (Coming soon)
  14. Check If a Date Is Today in JavaScript or Node.js

  15. Check If a Date is Tomorrow in JavaScript or Node.js

  16. Check If a Date is Yesterday in JavaScript or Node.js

  17. How to Format a Date YYYY-MM-DD in JavaScript or Node.js

  1. How to Run an Asynchronous Function in Array.map()

  2. How to Reset and Empty an Array

  3. Clone/Copy an Array in JavaScript and Node.js

  4. Get an Array With Unique Values (Delete Duplicates)

  5. Sort an Array of Integers in JavaScript and Node.js

  6. Sort a Boolean Array in JavaScript, TypeScript, or Node.js

  7. Check If an Array Contains a Given Value in JavaScript or Node.js

  8. Add an Item to the Beginning of an Array in JavaScript or Node.js

  9. Append an Item at the End of an Array in JavaScript or Node.js

  10. How to Exit and Stop a for Loop in JavaScript and Node.js

  11. Split an Array Into Smaller Array Chunks in JavaScript and Node.js

  12. How to Get an Index in a for…of Loop in JavaScript and Node.js

  13. How to Exit, Stop, or Break an Array#forEach Loop in JavaScript or Node.js

  14. Retrieve a Random Item From an Array in JavaScript or Node.js

  15. How to Reverse an Array in JavaScript and Node.js

  16. Sort an Array of Strings in JavaScript, TypeScript or Node.js

  17. Sort an Array of Objects in JavaScript, TypeScript or Node.js

  18. Check If a Value Is an Array in JavaScript or Node.js

  19. Join an Array of Strings to a Single String Value


    (Coming soon)


  1. How to Run an Asynchronous Function in Array.map()

  2. How to Reset and Empty an Array

  3. for…of vs. for…in Loops

  4. Clone/Copy an Array in JavaScript and Node.js

  5. Get an Array With Unique Values (Delete Duplicates)

  6. Sort an Array of Integers in JavaScript and Node.js

  7. Sort a Boolean Array in JavaScript, TypeScript, or Node.js

  8. Check If an Array Contains a Given Value in JavaScript or Node.js

  9. Add an Item to the Beginning of an Array in JavaScript or Node.js

  10. Append an Item at the End of an Array in JavaScript or Node.js

  11. How to Exit and Stop a for Loop in JavaScript and Node.js

  12. Split an Array Into Smaller Array Chunks in JavaScript and Node.js

  13. How to Get an Index in a for…of Loop in JavaScript and Node.js

  14. How to Exit, Stop, or Break an Array#forEach Loop in JavaScript or Node.js

  15. Retrieve a Random Item From an Array in JavaScript or Node.js

  16. How to Reverse an Array in JavaScript and Node.js

  17. Sort an Array of Strings in JavaScript, TypeScript or Node.js

  18. Sort an Array of Objects in JavaScript, TypeScript or Node.js

  19. Check If a Value Is an Array in JavaScript or Node.js

  20. Join an Array of Strings to a Single String Value

    (Coming soon)

  1. Callback and Promise Support in your Node.js Modules

  2. Run Async Functions/Promises in Sequence

  3. Run Async Functions/Promises in Parallel

  4. Run Async Functions in Batches

  5. How to Fix “Promise resolver undefined is not a function” in Node.js or JavaScript

  6. Detect if Value Is a Promise in Node.js and JavaScript

  7. Overview of Promise-Based APIs in Node.js


  1. Callback and Promise Support in your Node.js Modules

  2. Run Async Functions/Promises in Sequence

  3. Run Async Functions/Promises in Parallel

  4. Run Async Functions in Batches

  5. How to Fix “Promise resolver undefined is not a function” in Node.js or JavaScript

  6. Detect if Value Is a Promise in Node.js and JavaScript

  7. Overview of Promise-Based APIs in Node.js

  1. Human-Readable JSON.stringify() With Spaces and Line Breaks

  2. Write a JSON Object to a File

  3. Create a Custom “toJSON” Function in Node.js and JavaScript

  1. Human-Readable JSON.stringify() With Spaces and Line Breaks

  2. Write a JSON Object to a File

  3. Create a Custom “toJSON” Function in Node.js and JavaScript

  4. Securely Parse JSON

  1. Check If a Value Is Iterable in JavaScript or Node.js

  1. Check If a Value Is Iterable in JavaScript or Node.js

  1. Extend Multiple Classes (Multi Inheritance)

  2. Retrieve the Class Name at Runtime in JavaScript and Node.js

  1. Extend Multiple Classes (Multi Inheritance)

  2. Retrieve the Class Name at Runtime in JavaScript and Node.js

  1. Generate a Random Number in Range With JavaScript/Node.js

  2. Ensure a Positive Number in JavaScript or Node.js

  3. Check if a Number Is Infinity

  4. Check If a Number has Decimal Places in JavaScript or Node.js


    (Coming soon)

  5. Use Numeric Separators for Better Readability

  1. Generate a Random Number in Range With JavaScript/Node.js

  2. Ensure a Positive Number in JavaScript or Node.js

  3. Check if a Number Is Infinity

  4. Check If a Number has Decimal Places in JavaScript or Node.js

    (Coming soon)
  5. Use Numeric Separators for Better Readability

  1. How to Check if an Object is Empty in JavaScript or Node.js

  2. How to CamelCase Keys of an Object in JavaScript or Node.js

  3. How to Snake_Case Keys of an Object in JavaScript or Node.js

  4. How to Destructure a Dynamic Key in JavaScript or Node.js

  5. How to Get All Keys (Including Symbols) from an Object in JavaScript or Node.js

  6. How to Delete a Key From an Object in JavaScript or Node.js

  7. Iterate Through an Object’s Keys and Values in JavaScript or Node.js

  8. How to Convert URLSearchParams to Object

  9. Check If a Value Is an Object in JavaScript or Node.js

  10. Conditionally Add Properties to an Object in JavaScript or Node.js

  1. How to Merge Objects

  2. How to Check if an Object is Empty in JavaScript or Node.js

  3. How to CamelCase Keys of an Object in JavaScript or Node.js

  4. How to Snake_Case Keys of an Object in JavaScript or Node.js

  5. How to Destructure a Dynamic Key in JavaScript or Node.js

  6. How to Get All Keys (Including Symbols) from an Object in JavaScript or Node.js

  7. How to Delete a Key From an Object in JavaScript or Node.js

  8. Iterate Through an Object’s Keys and Values in JavaScript or Node.js

  9. How to Convert URLSearchParams to Object

  10. Check If a Value Is an Object in JavaScript or Node.js

  11. Conditionally Add Properties to an Object in JavaScript or Node.js

  1. Get a File’s Created Date

  2. Get a File’s Last Modified or Updated Date of a File

  3. How to Create an Empty File

  4. Check If a Path or File Exists

  5. Check If a Path Is a Directory

  6. Check If a Path Is a File

  7. Retrieve the Path to the User’s Home Directory

  8. Read File Content as String

  9. Check If a Directory Is Empty

  10. How to Create a Directory (and Parents If Needed)

  11. Get a File Name (With or Without Extension)

  1. Get a File’s Created Date

  2. Get a File’s Last Modified or Updated Date of a File

  3. How to Create an Empty File

  4. Check If a Path or File Exists

  5. How to Rename a File

  6. Check If a Path Is a Directory

  7. Check If a Path Is a File

  8. Retrieve the Path to the User’s Home Directory

  9. How to Touch a File

  10. Read File Content as String

  11. Check If a Directory Is Empty

  12. How to Create a Directory (and Parents If Needed)

  13. Get a File‘s Extension

  14. Get the Size of a File

  15. Get a File Name (With or Without Extension)

  16. Read a JSON File

  1. Create From Object

  2. Transform to an Object

  1. Determine the Node.js Version Running Your Script

  1. Determine the Node.js Version Running Your Script

  1. Check if a Value is a Symbol in JavaScript or Node.js

  1. Check if a Value is a Symbol in JavaScript or Node.js

  1. Detect if Running on Linux

  2. Detect if Running on macOS

  3. Detect if Running on Windows

  4. Check if Running on 64bit or 32bit Platform

  5. Constant for Platform-Specific Newline

  1. Detect if Running on Linux

  2. Detect if Running on macOS

  3. Detect if Running on Windows

  4. Check if Running on 64bit or 32bit Platform

  5. Constant for Platform-Specific Newline

  1. How to Download a File

  1. Retrieve the List of Supported Hash Algorithms

  1. Calculate an MD5 Hash

  2. Retrieve the List of Supported Hash Algorithms

  3. Calculate a SHA256 Hash

Fix “Uncaught SyntaxError” in the Browser

Browsers support modules out of the box. But you must tell the browser that imports using a <script> tag should be handled as a module. For example, frontend tools like Vite create a modern output bundle using modules.

Fix the syntax error by adding type="module" to your script tags:

<script type="module" src="/assets/app.js"></script>  

Fix “Uncaught SyntaxError” in Node.js

You must tell Node.js that you’re using modules when your code is using import or export keywords. Node.js in version 18.x uses CommonJS as the default, but CommonJS doesn’t support these keywords. You must run your app as a module. You can do that by setting the type: "module" of your app inside the package.json file:

package.json

{
  "type": "module"
}

This resolves the “Uncaught SyntaxError” in your Node.js application and you can write modern code using ECMAScript modules.

Enjoy!


Mentioned Resources

  • Browser module support guide on MDN
  • Vite website

Get Notified on New Future Studio
Content and Platform Updates

Get your weekly push notification about new and trending
Future Studio content and recent platform enhancements

Marcus Pöhls

Marcus is a fullstack JS developer. He’s passionate about the hapi framework for Node.js and loves to build web apps and APIs. Creator of Futureflix and the “learn hapi” learning path.

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

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Cannot resolve symbol string java ошибка
  • Cannot resolve symbol java intellij idea ошибка