Regrettably, the current version of .babelrc
does not offer a way to manipulate how Babel loads modules. However, there are various workarounds available to address this issue.
Babel has the capability to accept both strings and (module) objects as presets and plugins. This means you can either provide the module's name (causing Babel to attempt resolving and loading it using its internal mechanism), or load the module yourself and directly pass it to Babel.
The challenge arises when using .babelrc
since it is JSON, allowing solely the passing of the module's name and thereby subjecting you to Babel's default module-loading procedure.
If you employ webpack, you have the option to completely abandon the use of .babelrc
and instead pass options to Babel within the webpack configuration, similar to:
query: {
presets: [
'babel-preset-es2015',
'babel-preset-react',
'babel-preset-stage-0',
].map(require.resolve),
}
Refer to: How to set resolve for babel-loader presets
If working directly with Babel in your code, you can still utilize .babelrc
, but adjust the code responsible for interpreting it to load the presets and plugins by hand.
For instance, if you currently have the following code snippet reading .babelrc
:
var fs = require('fs');
var babelrc = fs.readFileSync('./.babelrc');
var config = JSON.parse(babelrc);
require('babel-core/register')(config);
You could modify it to something like:
var fs = require('fs');
var babelrc = fs.readFileSync('./.babelrc');
var config = JSON.parse(babelrc);
config.presets = config.presets.map(function(preset) {
return require.resolve('babel-preset-' + preset);
});
config.plugins = config.plugins.map(function(plugin) {
return require.resolve('babel-plugin-' + plugin);
});
require('babel-core/register')(config);