620

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",
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
user3810626
  • 6,798
  • 3
  • 14
  • 19
  • 3
    Hi, having the same problem right now. Could you also share your dependencies? Maybe even a diff before and after your update. I could check against mine to see if we can find similar packages which might cause the trouble. – stewo Oct 16 '19 at 11:33
  • 5
    I just replaced all the "imports" with "requires" and all is well now. Dumb but it wasn't worth the effort to figure it out right now. I will update the original with dependencies, though. If you get any leads, I'll check them out against my original code. – user3810626 Oct 16 '19 at 20:20
  • 4
    CommonJS syntax (require and module.exports) was the original format for node and webpack also supports it, but ES6 module syntax (export, import) is the newer way and now node and webpack support it. I read that node supports import now but so many tutorials show require for pure node stuff that it's likely better to use that syntax for node. – Ted Fitzpatrick Oct 16 '19 at 20:29
  • Hm, interesting, that preset only sets the {allowJs: true} setting. Same I also (already) added to the TS compilerOptions. Maybe you want to have a look into this. edit: omg, in case you actually use TS? ... what a config hell. – stewo Oct 16 '19 at 22:24
  • I used a package called package called `esm` to write the code in es6. https://www.npmjs.com/package/esm – Karthik Nov 21 '19 at 14:29
  • Please refer to my answer here https://stackoverflow.com/a/60611980/2941150 – Kuldeep Bhimte Mar 10 '20 at 05:26
  • 8
    `"type":"module"` doesn't solve my problem, and there are over a hundred of `imports`. Syntax of `require` is diff from `imports`, not an easy replace. Can you give an example of how `imports` is replaced by `requires`? – Jeb50 Aug 29 '20 at 22:13
  • The Powers That Be: A (mildly) comic way of saying "I don't know where this is being decided." – user3810626 Sep 09 '21 at 20:21
  • Something *seems* to be missing at the end (after `"babel-preset-es2015": "^6.24.1",`). Can you make it clearer? Either why nothing is actually missing or adding the missing part (including "`}`"). – Peter Mortensen Sep 10 '21 at 05:20
  • I cannot, alas. I remember the issue, and I remember getting around it in a really cheesy way, but I do not think I can recreate it now. – user3810626 Sep 11 '21 at 14:53
  • I had the same issue the last couple of days ... not a type:module issue ... not a config issue ... the issue was coming from the : cluster.fork(). (npm cluster module) I have no problem with the "master" instance but the children were "broken". as I'm in a dev environement... I don't care about clustring. – M. Gara May 16 '22 at 20:20

32 Answers32

719

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.

Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
jabacchetta
  • 45,013
  • 9
  • 63
  • 75
  • 3
    If I use this, then change the path to include the "js" for the required file, then change the format of the export statements in the required file, and then take all the "require" statements I changed from "import"—because now "require" is unknown—this will work, so I'll accept this answer. – user3810626 Apr 10 '20 at 22:32
  • 146
    This is not really an option if the problem is under node_modules/ right? Any ideas how to fix in that case? – Brandon Apr 15 '20 at 21:17
  • 5
    or use babel! ` module.exports = { presets: ['@babel/preset-env'], }; ` – Cocuba Jun 22 '20 at 12:38
  • I'm at node 14.9.0, VSC, added `"type":"module"` solved `express`. But now **did you mean to import env.js** for `import env from './env'` Seems like I have to edit every file? – Jeb50 Aug 29 '20 at 21:49
  • 1
    @Cocuba answer is spot on and should be the accepted answer because it actually transpiles. – Jason Rice Oct 07 '20 at 16:41
  • Yes this works fine to my case that trying to import React module. – Ben Nov 05 '20 at 11:52
  • 9
    This solution doesn't work if you're running ```.ts``` files. If you could add that simply using ```nodemon``` instead of ```node```, as per this answer https://stackoverflow.com/a/65058291/11664580 down below, it would hopefully save people the half a day I've spent messing around. Alternatively, installing ```ts-node``` seems to be a solution, as per https://stackoverflow.com/a/61947868/11664580 – JimmyTheCode Oct 22 '21 at 15:49
  • 1
    I had a hidden package.json in one of my source directories. Had to do a `find . -name package.json` and my imports started working. – James M. Lay Nov 16 '21 at 04:03
  • Adding `"type": "module"` isn't solving the error for me. – Ryan Jul 01 '22 at 20:04
  • I like the additional note about the .cjs extension. Very useful. – fool4jesus Oct 04 '22 at 23:35
  • my package.json file dont have a `{ "type":"module" }` it have `{ "dependencies": { "chalk": "^4.1.2", "discord.js": "^14.6.0", "express": "^4.18.2", "pureimage": "^0.3.14" } }` – coco bar Oct 19 '22 at 23:36
  • But when I add `type: module`, if I use require, I'll get an error: `ReferenceError: require is not defined in ES module scope, you can use import instead` – Nam Lee Nov 02 '22 at 22:37
  • It breaks eslint. `[eslint] Cannot read config file` – Oleg Abrazhaev Apr 21 '23 at 10:39
186

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.

Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
Dr-Bracket
  • 4,299
  • 3
  • 20
  • 28
112

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": { ...
  },
  ...
}
riQQ
  • 9,878
  • 7
  • 49
  • 66
L. Theodore Obonye
  • 1,221
  • 1
  • 6
  • 9
  • 1
    tx, but do you have an idea where I can find the package.json?? I am using netbeans. I also searched for package.json on my macbook but I see a lot of package.json files. Any tips? – alex Mar 11 '21 at 10:54
  • 1
    Hi Alex, it's been a while since worked in Java project but I hope that this link can give you a clue on where to locate the package.json file: https://stackoverflow.com/questions/41513559/netbeans-cant-run-package-json-on-maven-web-application – L. Theodore Obonye Mar 11 '21 at 11:19
  • 4
    But when I add `type: module`, if I use require, I'll get an error: `ReferenceError: require is not defined in ES module scope, you can use import instead` – Nam Lee Nov 02 '22 at 22:38
79

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
  • 27,717
  • 28
  • 128
  • 190
  • 45
    2020 update: `--experimental-modules` is no longer required. – Cullub Jun 10 '20 at 21:43
  • 8
    Not saying this answer is wrong, I've seen the same docs. But I don't see how the suggestion to use import() to access es6 module in CommonJS is useful. It's async and so can't be used to import anything at the file level. Which makes trying to access es6 modules from CommonJS painful to say the least. Considering that the main unit test frameworks Jasmine Jest etc don't handle this at all well it leaves me thinking that until there is better interop support the whole Node es6 situation seems half baked to me, but I'd love to be proven wrong. – Neutrino Sep 11 '20 at 21:05
  • add it where? Can we get a code example please. – john k Sep 22 '22 at 20:18
  • adding it breaks my 'require's `ReferenceError: require is not defined` – john k Sep 22 '22 at 20:23
  • @johnktejik [use `createRequire`](https://stackoverflow.com/a/59443582/316310) to define a function in an ESM file that works like `require()` does in CommonJS files. _(The opposite way around—CJS in ESM—is simply `const foo = await import('./some-module.js')`)_ – RickN Sep 23 '22 at 08:30
  • But when I add `type: module`, if I use require, I'll get an error: `ReferenceError: require is not defined in ES module scope, you can use import instead` – Nam Lee Nov 02 '22 at 22:38
  • See this [answer](https://stackoverflow.com/a/65784165/314114) for a code example using `import()`. – Andrew Philips Nov 26 '22 at 22:00
44

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
  • 30,738
  • 21
  • 105
  • 131
us_david
  • 4,431
  • 35
  • 29
  • Reading the Node.js documentation, `import` will handle both `ES` and `CommonJS` modules; `require` only handles `CommonJS` modules. https://nodejs.org/api/esm.html#import-expressions – Thomas David Kehoe Oct 23 '22 at 02:02
19

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
  • 30,738
  • 21
  • 105
  • 131
iseenoob
  • 339
  • 1
  • 8
16

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
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
Roque Orts
  • 310
  • 2
  • 11
16

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"
  }
}
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
Rohit Parte
  • 3,365
  • 26
  • 26
  • I had the same issue. As an alternative, simply running the package.json script using ```nodemon``` instead of ```node``` works too. Saves the need for installing another package (assuming you're already running nodemon). credit: https://stackoverflow.com/a/65058291/11664580 – JimmyTheCode Oct 22 '21 at 15:44
  • They should go to devDependencies instead. – OSGI Java Feb 03 '22 at 19:34
9

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
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
Abhishek Kumar
  • 197
  • 2
  • 15
  • +1 `esm` seems to be the easiest solution when you cannot add `"type": "module"` to the `package.json` file. – Ale Felix Sep 08 '21 at 02:31
9

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

David S
  • 383
  • 5
  • 6
  • 3
    I found this answer the most clear explanation to OP. Just that, say I'm writing an app, not a module, does _"Cannot use import statement outside a module"_ means that I cannot use the `import` statement to import anything, since I'm outside a module, right? This is still confusing. For _"Files including node modules must either end in .mjs or the nearest package.json file must contain "type": "module"."_, I'm writing an app, not a module, why I need to name my app with mjs or set my package to module? – xpt Feb 19 '22 at 21:46
  • 1
    @xpt Hey. So, you can't compare an app and a module. I think you maybe be thinking of it in terms of node modules which seems like a program within your program. This isn't really what a module is. Let me clarify what a module is and I think that'll solve your confusion: – David S Feb 20 '22 at 22:30
  • 1
    @xpt Think of it this way, you're writing an app and working on a file named main-file.js. You want to import a function from another file called some-other-file.js. some-other-file.js is quite large and you don't need the entire file. You just want a function from the file. Now if some-other-file.js and main-file.js were modules (.mjs), you could 'import' the function you so desire e.g. import someFunction from './some-other-file'. To sum it up, a module is a js file that can be separated by its functions so it can export particular functions opposed to the whole file. Does that make sense? – David S Feb 20 '22 at 22:48
  • 1
    Thanks for the explanation David. So I understand some-other-file.js is module, which can export particular functions opposed to the whole file. However, is main-file.js a module too? No, it's only my main of my app. Would the "Cannot use import statement outside a module" rule apply to main-file.js (since it is not a module)? – xpt Feb 21 '22 at 18:07
  • Anyway, I think I'd better ask a new question instead -- https://stackoverflow.com/questions/71240736/ – xpt Feb 23 '22 at 16:33
9

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);
});
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
Adrian
  • 341
  • 1
  • 3
  • 11
8

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.

Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
Luca C.
  • 11,714
  • 1
  • 86
  • 77
7

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
  • 30,738
  • 21
  • 105
  • 131
Gowtham
  • 499
  • 6
  • 9
6

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!

Update:

The problem is that node does not accept typescript files. Instead, ts-node might be the perfect replacement.

LSafer
  • 344
  • 3
  • 7
6

To use import, do one of the following.

  1. Rename the .js file to .mjs
  2. In package.json file, add {type:module}
Vidya Sagar H J
  • 157
  • 1
  • 3
3

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
  • 30,738
  • 21
  • 105
  • 131
Jitender Kumar
  • 2,439
  • 4
  • 29
  • 43
3

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',
},
Pieterjan
  • 2,738
  • 4
  • 28
  • 55
  • That works for me. Thks. But now i'm giving this error `The injectable 'PlatformLocation' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available` – alambertt Sep 14 '22 at 23:12
3

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

Daniel
  • 373
  • 4
  • 10
2

If you are using vite - react .js application with Speedy Web Compiler (SWC) and you tried to import the various methods of jest testing library ({import { describe, expect, test } from "@jest/globals";), all your test will run individually and outside the module. Hence you might get the error as :

SyntaxError: Cannot use import statement outside a module

Since you are using SWC, babel config won't help. So it could be resolved by just giving simple dev dependency:

npm install --save-dev @types/jest

Later remove the import statement, use methods (describe, test, expect, afterAll, afterEach, beforeAll, beforeEach, fail, fdescribe, fit, it, jasmine, jest, pending, spyOn, xdescribe, xit, xtest) directly since there are treated as globals. Install link and other documentation here! @types/jest

Test your sum.test.js by npm run test, supposing you have"test": "jest" in scripts commands and jest in dev dependency:

const sum = (val1, val2) => {
  return val1 + val2;
};

describe("sum module", () => {
  test("adds 1 + 2 to equal 3", () => {
    expect(sum(1, 2)).toBe(3);
  });
});
Clinto_92_Abraham
  • 333
  • 1
  • 3
  • 10
1

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
  • 30,738
  • 21
  • 105
  • 131
srghma
  • 4,770
  • 2
  • 38
  • 54
1

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
  • 30,738
  • 21
  • 105
  • 131
DINA TAKLIT
  • 7,074
  • 10
  • 69
  • 74
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

Ahmed Adewale
  • 2,943
  • 23
  • 19
1

For people coming to this thread due to this error in Netlify functions even after adding "type": "module" in package.json file, update your netlify.toml to use 'esbuild'. Since esbuild supports ES6, it would work.

[functions]
  node_bundler = "esbuild"

Reference: https://docs.netlify.com/functions/build-with-javascript/#automated-dependency-bundling

1

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
  • 30,738
  • 21
  • 105
  • 131
yo3hcv
  • 1,531
  • 2
  • 17
  • 27
0

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
  • 30,738
  • 21
  • 105
  • 131
Redmen Ishab
  • 2,199
  • 18
  • 22
0
  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
  • 30,738
  • 21
  • 105
  • 131
0

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
  • 30,738
  • 21
  • 105
  • 131
harika
  • 21
  • 3
0

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

Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
Chalom.E
  • 617
  • 5
  • 20
0

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
ncutixavier
  • 455
  • 5
  • 4
0

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
  • 30,738
  • 21
  • 105
  • 131
DariusV
  • 2,645
  • 16
  • 21
  • Please review *[Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/questions/285551/)* (e.g., *"Images should only be used to illustrate problems that* ***can't be made clear in any other way,*** *such as to provide screenshots of a user interface."*) and [do the right thing](https://stackoverflow.com/posts/71944570/edit) (it covers answers as well). Thanks in advance. – Peter Mortensen Oct 12 '22 at 23:49
0

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.

Stokely
  • 12,444
  • 2
  • 35
  • 23
-1

I had this problem in a fledgling Express API project.

The offending server code in src/server/server.js:

import express from 'express';
import {initialDonationItems, initialExpenditureItems} from "./DemoData";

const server = express();

server.get('/api/expenditures', (req, res) => {
  res.type('json');
  res.send(initialExpenditureItems);
});

server.get('/api/donations', (req, res) => {
  res.type('json');
  res.send(initialDonationItems);
});

server.listen(4242, () => console.log('Server is running...'));

Here were my dependencies:

{
  "name": "contributor-api",
  "version": "0.0.1",
  "description": "A Node backend to provide storage services",
  "scripts": {
    "dev-server": "nodemon --exec babel-node src/server/server.js --ignore dist/",
    "test": "jest tests"
  },
  "license": "ISC",
  "dependencies": {
    "@babel/core": "^7.9.6",
    "@babel/node": "^7.8.7",
    "babel-loader": "^8.1.0",
    "express": "^4.17.1",
    "mysql2": "^2.1.0",
    "sequelize": "^5.21.7",
    "sequelize-cli": "^5.5.1"
  },
  "devDependencies": {
    "jest": "^25.5.4",
    "nodemon": "^2.0.3"
  }
}

And here was the runner that threw the error:

nodemon --exec babel-node src/server/server.js --ignore dist

This was frustrating, as I had a similar Express project that worked fine.

The solution was firstly to add this dependency:

npm install @babel/preset-env

And then to wire it in using a babel.config.js in the project root:

module.exports = {
  presets: ['@babel/preset-env'],
};

I don't fully grok why this works, but I copied it from an authoritative source, so I am happy to stick with it.

Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
halfer
  • 19,824
  • 17
  • 99
  • 186
  • Yeah, my issue was that the code had a *bunch* of presets and I could never quite hit the balance right of things I wanted vs. things I didn't want/that broke stuff. – user3810626 May 05 '20 at 17:42
  • I've been pushing through confusing JS crashes all day @user3810626 - I suspect my problem is that I'm quite new to the language and the ecosystem, and I need to put some learning aside for now to get stuff working. Getting there... `:-)` – halfer May 05 '20 at 17:56
  • 2
    Good luck! It's a jungle out there! (I mean, literally, the JS ecosystem is a jungle...) – user3810626 May 05 '20 at 18:47
  • 2
    @user3810626 nodejs devs dont know how things work anymore. they just keep trying [so] solutions until something sticks – hjpotter92 Jun 23 '20 at 17:08
  • This seems to be truer in some communities than others. – user3810626 Jun 23 '20 at 22:47