简体   繁体   中英

Error when running Mocha with ES6 files in node_modules/

I have a file that uses ES6 syntax that causes the following error when I attempt to run Mocha:

import 'test';
^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:533:28)
    at Module._extensions..js (module.js:580:10)

I run my tests using the following npm command:

"test": "mocha --reporter progress --require babel-core/register tools/testSetup.js \"**/*_spec.jsx\""

Here is my .babelrc file:

{
  "presets": ["es2015", "react"]
}

The file that is using ES6 syntax is contained in node_modules/ under a private module that is referenced through git. Is there any way to run Mocha without having to manually remove ES6 syntax from this private module? All of the regular ES6 files within my project do not cause any issues when I run Mocha.

babel-register is the right approach, but unfortunately for you it ignores code in node_modules by default: https://babeljs.io/docs/usage/babel-register/#ignores-node_modules-by-default

You can pass an option to tell it not to do this as follows:

require("babel-register")({
  // This will override `node_modules` ignoring - you can alternatively pass
  // an array of strings to be explicitly matched or a regex / glob
  ignore: false
});

This won't work on the command line, so you may have to add that line of code to your testSetup.js file (Make it the first thing in the file) and remove --require babel-core/register from the command-line options.

There is already an issue filed with ts-node for this over here https://github.com/TypeStrong/ts-node/issues/617 . To summarize, by default, ts-node does not transpile node_modules packages. If your ts file has an import statement pointing to one of the node_module package, then following the dependency rule, ts-node will transpile it (if you are on node10 or higher.) If you are on node version less than 10, then you will end up with the above error anyways.

As blakeembrey mentioned in the above link,

TS Node does not compile files in node_modules by default. If you want to consume ES modules, you should update to a node.js version that supports ES modules natively, use something like esm or alter the default behaviour by changing --ignore.

In ideal case, you should not be having a npm package with ts files. It should be JS files. As mentioned here https://github.com/TypeStrong/ts-node#import-statements

npm i @babel/register -D

修改package.json

"mocha": "./node_modules/.bin/mocha --compilers js:@babel/register",

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM