Unexpected token import, can not set up ES6 in my

2019-08-21 20:24发布

问题:

I am trying to set up a simple ES6 project to play with mocha, chai and sinon in the Terminal. But whenever I try to npm run test, I keep getting an error:

/Users/UserName/workspace/UnitTesting/mocha-sinon-chai/src/App.spec.js:1
(function (exports, require, module, __filename, __dirname) { import should from "chai";
                                                          ^^^^^^
SyntaxError: Unexpected token import

Here are my:

1. Package.json:

{
  "name": "mocha-sinon-chai",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "directories": {
    "test": "tests"
  },
  "dependencies": {
    "chai": "^4.1.2",
    "chai-as-promised": "^7.1.1",
    "sinon": "^4.4.1"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "mocha": "^5.0.1"
  },
  "scripts": {
    "build": "babel src -d lib",
    "test": "mocha ./tests/*.spec.js"
  },
  "author": "",
  "license": "ISC"
}

2. .babelrc:

{
  "presets": ["env"]
}

3. Root folder structure:

4. App.spec.js:

import should from "chai";
import { findOne } from "../src/App.js";

describe("App.js", function() {
  it("should return true if predicate exists in the array", function() {
    findOne([1, 2, 3], 3).should().be.true;
  });
});

5. index.js is empty
6. App.js simply contains a normal JS function

I have checked many other similar issues here on Stackoverflow and GitHub and none of those solved my problem.

回答1:

Adding this --require babel-core/register to test script inside package.json solved the problem:

"scripts": {
    "build": "babel src -d lib",
    "test": "mocha ./tests/*.spec.js --require babel-core/register"
  },