machineghost
machineghost

Reputation: 35813

Using Babel's `sourceRoot` Doesn't Affect Imports

Currently I can do:

require('./frontend/src/components/SomeComponent');

But if I set the following in my webpack.config.js:

resolve: {
    root: path.resolve('frontend', 'src')
}

I can instead do:

require('components/SomeComponent');

The problem is, when I don't use Webpack (eg. in a test environment) all of my imports break. According to the Babel docs, the sourceRoot property sets the "root from which all sources are relative." This made me think I could add the following to my .babelrc to fix my imports:

"sourceRoot": "frontend/src"

... but no such luck. When I do require('components/SomeComponent'); in babel-node it fails. When I just use Babel to transpile the file, the require line is the same whether or not I set a sourceRoot.

So, my question is, is there any way (with or without sourceRoot) to simulate webpack's resolve.root in Babel?

P.S. I know there are several Babel plug-ins which address this problem, but all of the ones I've seen require you to add a ~ to the require path (which of course breaks imports in Webpack).

Upvotes: 1

Views: 577

Answers (1)

Izhaki
Izhaki

Reputation: 23586

Many project have webpack + babel, and in many projects you sometimes bypass webpack (as in your case - for tests).

In such cases, all the resolve aliases should live in babel.

There are plugins out there to allow one reading the configuration of the other (and similar plugins for eslint etc.).

Upvotes: 1

Related Questions