Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

The solutions offered in other related questions, such as including the proper presets (es2015) in .babelrc, are already implemented in my project.

I have two projects (lets call them A and B) which both use ES6 module syntax. In Project A, I'm importing Project B which is installed via npm and lives in the node_modules folder. When I run my test suite for Project A, I'm getting the error:

SyntaxError: Unexpected token import

Which is preceded by this alleged erroneous line of code from Project B:

(function (exports, require, module, __filename, __dirname) { import createBrowserHistory from 'history/lib/createBrowserHistory';

The iife appears to be something npm or possibly babel related since my source file only contains "import createBrowserHistory from 'history/lib/createBrowserHistory'; The unit tests in Project B's test suite runs fine, and if I remove Project B as a dependency from Project A, my test suite then (still using es6 imports for internal project modules) works just fine.

Full Stack Trace:

 SyntaxError: Unexpected token import
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:374:25)
    at Module._extensions..js (module.js:405:10)
    at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:138:7)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (actionCreators.js:4:17)
    at Module._compile (module.js:398:26)
    at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
    at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/ProjectA/src/components/core/wrapper/wrapper.js:28:23)
    at Module._compile (module.js:398:26)
    at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
    at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/ProjectA/src/components/core/wrapper/wrapperSpec.js:15:16)
    at Module._compile (module.js:398:26)
    at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
    at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at /ProjectA/node_modules/mocha/lib/mocha.js:219:27
    at Array.forEach (native)
    at Mocha.loadFiles (/ProjectA/node_modules/mocha/lib/mocha.js:216:14)
    at Mocha.run (/ProjectA/node_modules/mocha/lib/mocha.js:468:10)
    at Object.<anonymous> (/ProjectA/node_modules/mocha/bin/_mocha:403:18)
    at Module._compile (module.js:398:26)
    at Object.Module._extensions..js (module.js:405:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Function.Module.runMain (module.js:430:10)
    at startup (node.js:141:18)
    at node.js:980:3

Here is my test command from package.json:

"test": "mocha --compilers js:babel-core/register '+(test|src)/**/*Spec.js'"

This StackOverflow post is similar but doesn't offer a solution for my use of the command line: import a module from node_modules with babel but failed

If you are distributing a module on npm, you should only be distributing the transpiled version of that module. – loganfsmyth Jan 27, 2016 at 18:24 This project is very light-weight. It's intended mostly for my own use, or others if they have a transpiration process in place that can support it. I'm trying to achieve "vanilla es6" in these dependencies. – ThinkingInBits Jan 27, 2016 at 19:31 I think you forget to configure the babel in package.json. add those to your package.json "babel": { "presets": ["es2015"] } – Jacob Mar 15, 2017 at 2:54 Note: according to the documentation --compilers is not necessary, --require babel-register should be used instead: "If your ES6 modules have extension .js, you can npm install --save-dev babel-register and use mocha --require babel-register; --compilers is only necessary if you need to specify a file extension." – try-catch-finally Jul 7, 2017 at 10:02 Finally I was able to get this to work using "babel":{"presets": ["es2015"]} it was the last thing i was missing! – Brandon Oct 11, 2017 at 1:03
  • npm install babel-preset-es2015 --save-dev
  • Add .babelrc to the root of the project with contents:

    "presets": [ "es2015" ]

    Ensure that you are running mocha with the "--compilers js:babel-core/register" parameter.

    For Babel6/7+

  • npm install @babel/preset-env --save-dev
  • Add .babelrc to the root of the project with contents:

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

    Ensure that you are running mocha with the --compilers js:babel-register (Babel 6) or --compilers js:@babel/register (Babel 7) parameter

    For mocha version 7 or later, use --require babel-register or --require @babel/register respectively.

    @kolec This works. Even better though, create a mocha.opts file in the root of /test directory and add it there – Martin Dawson Jan 7, 2017 at 14:35 If you want to use es2016, keep in mind that es2016 in Babel "Only compiles what's in ES2016 to ES2015" so you need both es2016 and es2015 in your presets array – prauchfuss Feb 19, 2017 at 18:18

    The final solution:

    Add registerBabel.js: a separate file whose job is to require babel-core/register...

    require('babel-core/register')({
      ignore: /node_modules/(?!ProjectB)/
    

    Add an entry.js if your application also relies on babel-node. This acts as a wrapper for your es6 containing application.

    require('./registerBabel');
    require('./server'); // this file has some es6 imports
    

    You would then run your application with node entry

    For mocha testing, testHelper.js should require registerBabel.js as well to initialize babel support at run time.

    require('./registerBabel');
    

    And run your mocha tests with mocha --require ./testHelper.js '+(test)/**/*Spec.js'

    This will recursively test any file ending in "Spec.js" within "./test". Substitute the pattern with one matching the specs in your project.

    It seems that ignore regex is a little off. I had to add an escaping backslash right after node_modules: ignore: /node_modules\/(?!ProjectB)/ in order for the babelRegister file to work. Otherwise seems great! – hellatan Nov 5, 2016 at 1:10 This doesn't allow us to use Rollupify because of the require statements. Would you know of a way of doing this without using the require statements? – MikesBarto2002 Nov 15, 2016 at 17:31 This is great, but what about tools that don't allow to add code like this and want to run your files directly. Then you end up with babel-node which doesn't allow such a thing using .babelrc. – Evgeny Dec 2, 2016 at 9:22 your awesome! Babel was processing my ES6 code when just running the server, but mocha testing would fail. Your answer solved it. I tried --compilers in mocha.opts but that caused the import statements to fail. – Energetic Pixels Jul 18, 2017 at 0:27 I couldn't get this to work, but it turned out I also needed to extend my babelrc: ``` require('@babel/register')({ extends: './.babelrc', ignore: [/node_modules\/(?!ProjectB)/] }); ``` – TiggerToo May 9, 2019 at 20:32

    Well sure you will have that issue, you are using ES6 that mocha don't know

    So you are using babel but you don't use it in your test...

    Few Solutions:

    A. if you running with NPM use

    "test": "mocha --compilers js:babel-core/register test*.js"

    B. I'm using

    "test": "./node_modules/.bin/mocha --compilers js:babel-core/register **/*spec.jsx"

    C. From cli:

    mocha --compilers js:babel-core/register test*.js

    You can read more at http://www.pauleveritt.org/articles/pylyglot/es6_imports/

    @ThinkingInBits What did you end up using, how did you (if you did) resolve the issue? I'm having severe trouble here, tried most of these options – Milan Velebit Nov 23, 2017 at 10:35

    I ran into that same issue. Having tried every other solution on stackoverflow and beyond, adding this simple config on package.json did it for me:

      "babel": {
        "presets": [
          "es2015"
    

    All my ES6 imports worked after that. By the way, I had this same configuration inside webpack.config.js, but apparently this was the only way to make it work for mocha testing as well.

    Hope this helps someone.

    i had a .babelrc file spelled incorrectly, so it wasn't working initially. This solution works and is the recommended solution. Create a .babelrc file in your project and add {"presets":["es2015"]} – AfDev Oct 30, 2016 at 12:18 This was generated by Webpacker for Rails: ``` "presets": [ [ "env", { "modules": false, "targets": { "browsers": "> 1%", "uglify": true }, "useBuiltIns": true } ], "react" ``` Once I removed the modules line, it worked for me. – Petercopter Oct 18, 2017 at 16:41 This solved my problem when CircleCI was failing to run my jest unit tests and giving me the unexpected token import error. +1 ! – Candlejack Jan 15, 2018 at 12:01

    I had the same issue and fixed it by reading from the babel documentation for integrating Babel with Mocha :

    "scripts": { "test": "mocha --compilers js:babel-register"

    For anybody using Babel 7 and Mocha 4, some of the package names have changed a bit and the accepted answer is a bit out-dated. What I had to do was:

    npm install @babel/register --saveDev

    and adding --require @babel/register to the test line in package.json

    "test": "./node_modules/mocha/bin/mocha --require @babel/polyfill --require @babel/register './test/**/*.spec.js'"

    The @babel/polyfill fixes some things like async/await functionality if you happen to be using those.

    Hope that helps somebody :)

    I'm adding another ES6+mocha+babel config answer here, current as of June '19 (refer to dates on answer/commente). mocha has deprecated the --compiler flag, and the version that I'm using has that unavailable even with --no-deprecation flag, c.f. this

    Note that I won't include all of the relevant bits from the linked pages, because none of them got me to a clean test build based on the latest versions of mocha and babel; this answer should include the steps that got me to a successful test build.

    Following the instructions here, and in this answer, and here, I tried installing what appeared to be the minimum latest babel using npm install:

    $ npm install --save-dev mocha
    $ npm install --save-dev @babel/preset-env
    

    And I adjusted the mocha invocation in package.json, like so:

    "scripts": {
        "test": "mocha --compilers js:@babel/register"
    

    This led to errors:

    × ERROR: --compilers is DEPRECATED and no longer supported.
    

    As above, --no-deprecation didn't help, please reference the page linked above. So following the instructions from here I adjusted package.json:

    "scripts": {
        "test": "mocha --require js:@babel/register"
    

    And started seeing errors about locating babel modules, such as:

    × ERROR: Cannot find module '@babel/register'
    

    At this point I started installing babel packages until I could progress. I believe that the full install is something like:

    $ npm install --save-dev @babel/preset-env @babel/register @babel/core
    

    The last change required was to update the mocha invocation in package.json, removing the js: prefix, like so:

    "scripts": {
        "test": "mocha --require @babel/register"
    

    I can't answer why this was necessary: if someone can answer this please leave a comment and I'll update my answer with better information.

    The last thing that I did was create a .babelrc in the project directory, with the contents:

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

    I can't recall what prompted this, but I believe that it was because mocha continued to complain about not recognizing the import keyword in my test.js. As above, if someone can answer this please leave a comment and I'll update my answer with better information.

    At this point I can run my mocha tests successfully. I realize that there are gaps in my knowledge here: I've written a lot of production javascript code but I'm a relative node noob. Anyone that sees this with more to add to the answer, please leave a comment and I'll improve the answer, OR leave your own better answer. – pb2q Jun 22, 2019 at 23:26
      "scripts": {
        "test": "mocha --require babel-core/register ./test/**/*.js -r ./test-setup.js"
      

    DeprecationWarning: "--compilers" will be removed in a future version of Mocha; see https://git.io/vdcSr for more info

    I therefore replaced it with the --require flag

    "test":  "mocha --require babel-core/register --recursive"
    

    Here's my .babelrc:

    "presets": ["env"]

    My package.json dev dependencies

    "devDependencies": {
      "babel-cli": "^6.26.0",
      "babel-preset-env": "^1.7.0",
      "mocha": "^5.2.0",
    

    I found the easiest way to do with with babel 6.X.X was to use nyc and then add in a helper file into the pckage.json

    So here is what I used

    package.json

    "scripts": { "test": "nyc mocha --reporter tap 'test/**/*.spec.js'" "devDependencies": { "babel-cli": "^6.24.0", "babel-core": "^6.24.0", "babel-loader": "^6.4.0", "babel-preset-env": "^1.2.2", "babel-preset-es2015": "^6.24.0", "babel-preset-react": "^6.23.0", "babel-preset-react-hmre": "^1.1.1", "babel-preset-stage-2": "^6.22.0", "babel-register": "^6.24.0", "babel-runtime": "^6.23.0", "chai": "^3.5.0", "mocha": "^3.2.0", "nyc": "^10.1.2", "webpack": "^2.3.3", "webpack-config": "^7.0.0", "webpack-dashboard": "^0.3.0", "webpack-dev-server": "^2.4.2" "nyc": { "all": true, "include": [ "src/**/*.js" "cache": true, "require": [ "./test/helper/registerBabel.js"

    babelrc

    "presets": [ "es2015", //remove the {modules: false} it doesn't work with this "stage-2"

    registerBabel.js

    /* eslint-disable import/no-commonjs, import/unambiguous */
    require('babel-register')();
    

    Now you will be able to use es6 in your tests or wherever you need to. Mine are all failing ;)

    Then npm run test which will fire off nyc mocha --reporter tap 'test/**/*.spec.js'

    "scripts": {
        "test": "mocha --require @babel/register --require @babel/polyfill src/DesktopApplication/Tests",
    

    .babelrc

    "presets": ["@babel/env"]

    I resolved this issue this morning with the following instructions from the official Using Babel instructions for Mocha 4:

    Install NPM Modules

    npm install --save-dev babel-polyfill
    npm install --save-dev babel-preset-env
    npm install --save-dev babel-register
    

    or a single command:

    npm i -d babel-polyfill babel-preset-env babel-register
    

    package.json:

    "scripts": {
        "test": "mocha --require babel-polyfill --require babel-register"
    

    .babelrc

    "presets": ["env"]

    You might need to specify the extensions option if you're using TypeScript:

    require("@babel/register")({
      extensions: ['.jsx', '.js', '.ts', '.tsx']
    

    I installed mocha and met the exact same error when I use import in my code. By doing the following actions, the issue was fixed.

    npm install babel-core --save-dev
    npm install babel-preset-es2015 --save-dev
    npm install babel-preset-stage-0 --save-dev
    

    And then add a .babelrc file:

    "presets": [ "es2015"

    And then run mocha in this way:

    mocha --compilers js:babel-core/register
    

    I had the same problem. When running tests I realized I actually wanted to stub dependent modules. It's good for unit testing and prevents babel from transforming submodules. So I used proxyquire, namely:

    const proxyquire = require('proxyquire').noCallThru()
    const myTestedModule = proxyquire('../myTestedModule', {
        'dependentModule1': { //stubbed module1 },
        'dependentModule2': { //stubbed module2 }
                    I guess this answer is practically not related to this question.. or rather, it could be added as a comment to another answer
    – 62mkv
                    Dec 17, 2016 at 16:04
    
  •