Trying ES6 style import gives 'Cannot use import statement outside a module'
Asked Answered
S

7

43

I am trying to write a javascript test in intellij for which I need to import some dependancies and I want to use ES6 style import statements but getting error

/usr/local/bin/node /workspace/rr-sample/node_modules/mocha/bin/_mocha
--ui bdd --reporter "/Users/me/Library/Application Support/IntelliJIdea2019.1/NodeJS/js/mocha-intellij/lib/mochaIntellijReporter.js"
tests/*.test.js /workspace/rr-sample/tests/App.test.js:3
import chai from 'chai'
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1043:16)
    at Module._compile (internal/modules/cjs/loader.js:1091:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1160:10)
    at Module.load (internal/modules/cjs/loader.js:976:32)
    at Function.Module._load (internal/modules/cjs/loader.js:884:14)
    at Module.require (internal/modules/cjs/loader.js:1016:19)
    at require (internal/modules/cjs/helpers.js:69:18)
    at /workspace/rr-sample/node_modules/mocha/lib/mocha.js:334:36
    at Array.forEach (<anonymous>)
    at Mocha.loadFiles (/workspace/rr-sample/node_modules/mocha/lib/mocha.js:331:14)
    at Mocha.run (/workspace/rr-sample/node_modules/mocha/lib/mocha.js:809:10)
    at Object.exports.singleRun (/workspace/rr-sample/node_modules/mocha/lib/cli/run-helpers.js:108:16)
    at exports.runMocha (/workspace/rr-sample/node_modules/mocha/lib/cli/run-helpers.js:142:13)
    at Object.exports.handler (/workspace/rr-sample/node_modules/mocha/lib/cli/run.js:292:3)
    at Object.runCommand (/workspace/rr-sample/node_modules/yargs/lib/command.js:242:26)
    at Object.parseArgs [as _parseArgs] (/workspace/rr-sample/node_modules/yargs/yargs.js:1087:28)
    at Object.parse (/workspace/rr-sample/node_modules/yargs/yargs.js:566:25)
    at Object.exports.main (/workspace/rr-sample/node_modules/mocha/lib/cli/cli.js:68:6)
    at Object.<anonymous> (/workspace/rr-sample/node_modules/mocha/bin/_mocha:10:23)
    at Module._compile (internal/modules/cjs/loader.js:1121:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1160:10)
    at Module.load (internal/modules/cjs/loader.js:976:32)
    at Function.Module._load (internal/modules/cjs/loader.js:884:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:67:12)
    at internal/main/run_main_module.js:17:47

What exactly is the issue? I found this link (and others) http://xahlee.info/js/js_import_export.html which tells you how to fix this error but in another context which doesn't help me, and it doesn't explain what the problem is.

In case it is helpful here is the code I am using.

//const chai = require("chai");
import chai from 'chai'

const React = require("react");
const expect = chai.expect;

describe('how it works first-time test', () => {
  it('checks equality', () => {

    const val = false;
    expect(val).to.be.false;
  });

});
Sheet answered 26/11, 2019 at 2:11 Comment(1)
“it doesn't explain what the problem is” — it does explicitly say “If your code uses import or export, then it must be loaded as module.” along the part where it says that you must use type="module". Have you seen Intellij Idea Ecmascript Harmony modules syntax?Zarah
O
28

The easiest way to run Mocha tests written in ES6 is compiling them on-the-fly using Mocha --require @babel/register option (see https://github.com/mochajs/mocha/wiki/compilers-deprecation#what-should-i-use-instead-then). Of course, you need to make sure to install the corresponding modules and set up the .babelrc accordingly

package.json:

"dependencies": {
  "@babel/cli": "^7.7.4",
  "@babel/core": "^7.7.4",
  "@babel/preset-env": "^7.7.4",
  "@babel/register": "^7.7.4",
...
}

.babelrc:

{
  "presets": [
    [
      "@babel/preset-env"
    ]
  ]
}

enter image description here

See also https://dev.to/bnorbertjs/my-nodejs-setup-mocha--chai-babel7-es6-43ei

Officer answered 26/11, 2019 at 10:16 Comment(4)
Important for me was the Extra Mocha OptionsGleam
it's Mocha run configuration, you can find it in Run > Edit Configurations...Officer
Worked for me, didn't use the config he has in the screenshotIndevout
Dogshit solution way too much complexityChalybeate
F
23

I had the same problem when updating one of my ts libraries to es6 modules instead of commonjs. After the change in the tsconfig.json my npm run test produced the mentioned error.

import chai from 'chai'
^^^^^^
SyntaxError: Cannot use import statement outside a module

I solved it without babel by adding an own tsconfig file just for testing.

tsconfig.testing.json

{
  "compilerOptions": {
      "module": "commonjs",
      "target": "es6"
  },
  "include": ["**/*.spec.ts"]
}

To run the tests via script in package.json

"test": "cross-env TS_NODE_PROJECT=\"tsconfig.testing.json\" mocha -r ts-node/register src/**/*.spec.ts",

(cross-env to set the env variable os independent)

Flense answered 18/11, 2020 at 16:15 Comment(7)
Note that cross-env is in maintenance modeTizes
@pixel, can you please add how this is relevant, thank youFlense
some people might want to stick to up to date / actively maintained libs - my comment was intended for those peopleTizes
Maintenance mode basically means no new features will be added, just bugfixes if necessary. It stays relevant for the usecase above. See more info and find alternatives at github.com/kentcdodds/cross-env/issues/257Flense
Did it not work without the tsconfig change? I just had the same issue and this script corrected it without any additional changes: "test": "mocha -r ts-node src/**/*.test.ts"Jamajamaal
cross-env is only needed if you're running Windows.Scurf
cross-env can be a solution if ANYONE, working on the project, is running windowsFlense
S
9

I was able to get this working by adding a .mocharc.yaml file at the source of my project with the following:

require: '@babel/register'

source: https://github.com/mochajs/mocha-examples/tree/master/packages/babel

Senegambia answered 9/7, 2020 at 21:52 Comment(3)
This was enough for me to be able to run in webstorm by right clicking on it and describeDutyfree
This solved issue of import but now having another issue of test coverage dropped from 97% to 10%Undermanned
@Ashish Kamble If you don't import any file you'll have full coverage. It's like if you don't write any code you won't have any bugsBrander
G
2

The cause of my issue was - an old version of Mocha, in fact any <6.0.0, even when the 'require: @babel/register' was configured. I updated Mocha to 9.0.0, I also updated Babel libraries to the latest and the problem was solved.

As it is also suggested in the Mocha docs, use config file, like '.mocharc.js', where you have to declare required Babel dependancy like in this example:

.mocharc.js

module.exports = {
  ...
  require: '@babel/register',
  ...
}

package.json

{
  ...
  "devDependencies": {
    "@babel/core": "^7.9.0",
    "@babel/preset-env": "^7.3.4",
    "@babel/preset-react": "7.18.6",
    "@babel/register": "^7.9.0"
    ...
    "mocha": "^9.0.0",
  }
}
Graz answered 28/9, 2022 at 22:16 Comment(0)
M
0

According to the doc:

https://nodejs.org/api/esm.html#esm_code_import_code_statements

So you have to ensure execute the script as an es module.

e.g. Execute the script using babel-node instead of Nodejs to enable the es6 or newer.

Moonlight answered 26/11, 2019 at 2:52 Comment(1)
The question is ask about to use Typescript in Mocha. Not in the AppUnderstand
V
0

enter image description here

For me, I was not able to run it via inline debug option in intellj. So I set extra mocha option and this solved the issue.

--compilers js:babel-core/register

Also, to run via terminal

npx mocha  --compilers js:babel-core/register
Vitiligo answered 10/5, 2022 at 10:48 Comment(1)
--compilers is deprecated.Moeller
S
0

There is one edge case that can cause this error that is worth mentioning, because I lost quite a bit of my life to troubleshooting it. I had accidentally done a yarn install inside of my src folder. My unit test command from package.json is:

"test:unit": "./node_modules/.bin/mocha \"src/**/*.spec.js\"",

And the error message had a subtle hint in it that took me a while to see (i.e. the file causing this import error was inside of src/node_modules) :

/Users/jeff/src/my-proj/src/node_modules/camel-case/dist.es2015/index.spec.js:1
import { camelCase, camelCaseTransformMerge } from ".";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:360:18)
    at wrapSafe (node:internal/modules/cjs/loader:1078:15)
    at Module._compile (node:internal/modules/cjs/loader:1113:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1203:10)
... (omitted for brevity) ...

Once I deleted the node_modules folder that was out of place (and left the one that's in the root of my project), mocha began to run MY tests, and not someone else's, and the error message went away!

Semple answered 18/9, 2023 at 22:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.