Reputation: 34
How can I tell babel to transpile files that are not in current (root) directory?
Here is my project structure:
|-project
|build
|-node_modules
-.babel.rc
-package.json
|src
|test
My source files are in "src", my test files are in "test".
I want to run mocha test from my package json script. I use babel to transpile my src files (ES6, React) on the fly.
Here is my package.json:
"scripts": {
"test": "mocha --require @babel/register '../test/**/*Test.js'"
}
and .babelrc:
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
]
}
But when I run yarn test, I get error message like this:
/src/App.spec.js:1
(function (exports, require, module, __filename, __dirname) { import React from 'react';
^^^^^^
SyntaxError: Unexpected token import
I'v tried milion config combination, but nothing works, I don't want to have package.json and babel config files in the project root (that works) and I couldn't figure it out how to tell babel what to transpile, without changing project structure.
Upvotes: 0
Views: 581
Reputation: 34
I finally came to this solution:
package.json:
"test": "NODE_PATH=$PWD/node_modules:$PWD/../src/ mocha --require babelRegister.js ../test/**/*.spec.js"
babelRegister.js:
require('@babel/register')({
extends: './.babelrc',
ignore: [/node_modules/],
});
Both "extends" and "ignore" must be set, otherwise it's not working. Looks hackish but I didn't find better solution.
Upvotes: 0
Reputation: 2355
From the error you posted, it seems your babel configuration cannot process jsx syntax. You can resolve this by installing @babel/plugin-transform-react-jsx
plugin.
And configuring it like so:
.babelrc
{
...
"plugins": ["@babel/plugin-transform-react-jsx"]
}
Upvotes: 0