Ad

Babel Not Transpile Files From Parent Dir

- 1 answer

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.

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad