mocha是node的構(gòu)建工具,默認只支持commonJS的模塊系統(tǒng),即require,exports,如何兼容ES6的模塊import,export呢
使用babel進行轉(zhuǎn)換
使用babel的方法之一就是通過require鉤子,即使用babel-register,babel-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)容是兩點:
- 如果需要對特殊的擴展名文件特殊的處理,就使用
--compile - 如果只是要支持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,當然還有mocha和chai,這邊preset也可以使用babel-preset-env
