Webstorm中mocha测试框架适配es6语法

1,041 阅读1分钟

问题描述

在web storm(idea也类似)在使用mocha(jest等其他框架也类似)中使用es6语法,无法通过测试,会报错。本文对此问题进行配置解决。

//报错形式如下
import assert from "assert";
^^^^^^
​
SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1116:16)
    at Module._compile (internal/modules/cjs/loader.js:1164:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
    at Module.load (internal/modules/cjs/loader.js:1049:32)
    at Function.Module._load (internal/modules/cjs/loader.js:937:14)
    at Module.require (internal/modules/cjs/loader.js:1089:19)
    at require (internal/modules/cjs/helpers.js:73:18)
    at Object.exports.requireOrImport (/home/chriego/Projects/personal/my-project/frontend/node_modules/mocha/lib/esm-utils.js:20:12)
    at Object.exports.loadFilesAsync (/home/chriego/Projects/personal/my-project/frontend/node_modules/mocha/lib/esm-utils.js:33:34)
    at Mocha.loadFilesAsync (/home/chriego/Projects/personal/my-project/frontend/node_modules/mocha/lib/mocha.js:421:19)
    at singleRun (/home/chriego/Projects/personal/my-project/frontend/node_modules/mocha/lib/cli/run-helpers.js:156:15)
    at exports.runMocha (/home/chriego/Projects/personal/my-project/frontend/node_modules/mocha/lib/cli/run-helpers.js:225:10)
    at Object.exports.handler (/home/chriego/Projects/personal/my-project/frontend/node_modules/mocha/lib/cli/run.js:366:11)
    at /home/chriego/Projects/personal/my-project/frontend/node_modules/mocha/node_modules/yargs/lib/command.js:241:49Process finished with exit code 1

解决方法

  1. 全局安装
npm install --save-dev babel-core babel-preset-es2015
  1. 配置.babelrc
//.babelrc
{
  "presets": [ "es2015" ]
}
  1. 菜单 -> Run -> Edit Configurations

image-20210728180441217.png

image-20210728180533140.png

  1. 添加Extra Mocha options
--compilers js:babel-core/register

image-20210728180619215.png

Apply后生效

image-20210728180641925.png

以上。

参考文档