mocha兼容ES6

mocha是node的构建工具,默认只支持commonJS的模块系统,即require,exports,如何兼容ES6的模块import,export呢

使用babel进行转换

使用babel的方法之一就是通过require钩子,即使用babel-registerbabel-register的作用是在把自身的require和commonJS的require绑定,之后每次require进来的文件都会被自动编译

require('babel-register')
// 之后require的文件都会被编译

可以通过制定option来定制babel-register的行为,这边直接拿官方文档的demo

require("babel-register")({
  // Optional ignore regex - if any filenames **do** match this regex then they
  // aren't compiled.
  ignore: /regex/,

  // Ignore can also be specified as a function.
  ignore: function(filename) {
    if (filename === "/path/to/es6-file.js") {
      return false;
    } else {
      return true;
    }
  },

  // Optional only regex - if any filenames **don't** match this regex then they
  // aren't compiled
  only: /my_es6_folder/,

  // Setting this will remove the currently hooked extensions of .es6, `.es`, `.jsx`
  // and .js so you'll have to add them back if you want them to be used again.
  extensions: [".es6", ".es", ".jsx", ".js"],

  // Setting this to false will disable the cache.
  cache: true
});

注意,默认会忽视node_module的文件,如果需要编译,需要通过option的ignore来支持

require("babel-register")({
  // This will override `node_modules` ignoring - you can alternatively pass
  // an array of strings to be explicitly matched or a regex / glob
  ignore: false
});

require进来的文件只有一下几种后缀的文件会进行编译.es6, .es, .jsx.js

你也可以使用在option中使用plugins和presets,但是如果.babelrc也配置了,.babelrc的优先级会更高

mocha的配置

mocha相关的cli参数主要有两个--compile--require,在官方文档的说明是这样的

--compilers
CoffeeScript is no longer supported out of the box. CS and similar transpilers may be used by mapping the file extensions (for use with --watch) and the module name. For example --compilers coffee:coffee-script with CoffeeScript 1.6- or --compilers coffee:coffee-script/register with CoffeeScript 1.7+.

About Babel

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.

主要内容是两点:

  1. 如果需要对特殊的扩展名文件特殊的处理,就使用--compile
  2. 如果只是要支持ES6的模块系统,只需要--require babel-register

在实际使用中,两种方式都可以

mocha --require babel-register
mocha --compile js:babel-register

还有一个非常重要的一点是,需要对babel的presets进行设置,所以还需要一个babel-preset-es2015

可以在package.json设置,或者使用.babelrc

// package.json
//...
  "babel": {
    "presets": [
      "es2015"
    ]
  },

总结

在mocha中使用ES6的module需要babel-registerbabel-preset-es2015,当然还有mochachai,这边preset也可以使用babel-preset-env

mocha兼容ES6_第1张图片
image.png

你可能感兴趣的:(mocha兼容ES6)