Babel unexpected token import when running mocha tests

前端 未结 17 1542
Happy的楠姐
Happy的楠姐 2020-11-27 14:40

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 projec

17条回答
  •  伪装坚强ぢ
    2020-11-27 15:03

    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.

提交回复
热议问题