Babel7でES6のテストをmochaで走らせようとすると Cannot find module 'babel-core/register'
Babel7でES6のテストをするためにmochani --compilers js:babel-core/register"
をつけて実行したところ以下のエラーが起きました。
$ yarn run test yarn run v1.5.1 (node:86730) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead. $ mocha --compilers js:babel-core/register internal/modules/cjs/loader.js:583 throw err; ^ Error: Cannot find module 'babel-core/register' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15) at Function.Module._load (internal/modules/cjs/loader.js:507:25) at Module.require (internal/modules/cjs/loader.js:637:17) at require (internal/modules/cjs/helpers.js:20:18) at program.compilers.forEach.c (/Users/asmsuechan/src/bot/node_modules/mocha/bin/_mocha:503:3) at Array.forEach (<anonymous>) at Object.<anonymous> (/Users/asmsuechan/src/bot/node_modules/mocha/bin/_mocha:495:19) at Module._compile (internal/modules/cjs/loader.js:689:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10) at Module.load (internal/modules/cjs/loader.js:599:32) at tryModuleLoad (internal/modules/cjs/loader.js:538:12) at Function.Module._load (internal/modules/cjs/loader.js:530:3) at Function.Module.runMain (internal/modules/cjs/loader.js:742:12) at startup (internal/bootstrap/node.js:236:19) at bootstrapNodeJSCore (internal/bootstrap/node.js:560:3) error An unexpected error occurred: "Command failed. Exit code: 1 Command: sh Arguments: -c mocha --compilers js:babel-core/register Directory: /Users/asmsuechan/src/bot Output: ". info If you think this is a bug, please open a bug report with the information provided in "/Users/asmsuechan/src/bot/yarn-error.log". info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
以下のような設定です。
// package.json "scripts": { "test": "mocha --compilers js:babel-core/register", "deploy": "serverless deploy", "build": "babel scripts/* -d dist" }, "devDependencies": { "@babel/cli": "^7.1.5", "@babel/core": "^7.1.5", "@babel/preset-env": "^7.1.5", "aws-sdk": "^2.9.0", "chai": "^3.5.0", "chai-as-promised": "^6.0.0", "mitt": "^1.1.3", "mocha": "^5.2.0", "sinon": "^7.1.1" } // .babelrc { "presets": [ [ "@babel/preset-env" ] ] }
解決
Babel公式の Upgrade to Babel 7 に書いてありました。
The deprecated usage of babel-core/register has been removed in Babel 7; instead use the standalone package @babel/register.
yarn add --dev @babel/register
してscriptsを"test": "mocha --compilers js:@babel/register"
としたら通るようになりました。
なお、mochaの --compilers
オプションはいずれ使えなくなるらしいので --require @babel/register
にしましょう。