意外的令牌进口,不能设置ES6在我的摩卡,湾仔及兴农JS项目(Unexpected token im

2019-11-04 14:21发布

我想建立一个简单的ES6项目,摩卡,薛宝钗和兴农在终端发挥。 但每当我试图npm run test ,我不断收到一个错误:

/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

这里是我的:

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.根文件夹结构:

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是空的
6. App.js简单地包含一个正常JS功能

我已经#2和GitHub上这里检查过很多其他类似的问题,这些都不解决我的问题。

Answer 1:

添加此--require babel-core/register测试脚本中的package.json解决了这个问题:

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


文章来源: Unexpected token import, can not set up ES6 in my JS project with Mocha, Chai and Sinon