mocha兼容ES6

mocha是node的構(gòu)建工具,默認只支持commonJS的模塊系統(tǒng),即require,exports,如何兼容ES6的模塊import,export呢

使用babel進行轉(zhuǎn)換

使用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的優(yōu)先級會更高

mocha的配置

mocha相關(guān)的cli參數(shù)主要有兩個--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.

主要內(nèi)容是兩點:

  1. 如果需要對特殊的擴展名文件特殊的處理,就使用--compile
  2. 如果只是要支持ES6的模塊系統(tǒng),只需要--require babel-register

在實際使用中,兩種方式都可以

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

還有一個非常重要的一點是,需要對babel的presets進行設(shè)置,所以還需要一個babel-preset-es2015

可以在package.json設(shè)置,或者使用.babelrc

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

總結(jié)

在mocha中使用ES6的module需要babel-register,babel-preset-es2015,當然還有mochachai,這邊preset也可以使用babel-preset-env

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容