diff --git a/README.md b/README.md index 16d362b5..bc9952c6 100644 --- a/README.md +++ b/README.md @@ -193,6 +193,38 @@ In the case one of your dependencies is installing `babel` and you cannot uninst } ``` +## Customize config for specific Webpack target + +Webpack supports bundling for multiple different [targets](https://webpack.js.org/concepts/targets/) including the web, and node. Sometimes it can be useful to have a slightly different babel configuration for the different environments. This loader provides a `target` property via the babel [caller](https://babeljs.io/docs/en/config-files#apicallercb) API which can be used for just this case: + +```javascript +// babel.config.js + +module.exports = api => { + return { + plugins: [ + "@babel/plugin-proposal-nullish-coalescing-operator", + "@babel/plugin-proposal-optional-chaining" + ], + presets: [ + [ + "@babel/preset-env", + { + useBuiltIns: "entry", + // caller.target will be the same as the target option from webpack + ...(api.caller(caller => caller.target === "node") + ? { node: "current" } + : { targets: { chrome: "58", ie: "11" } } + ) + } + ] + ] + } +} +``` + +In the above `babel.config.js` we're able to distinguish if we are transpiling for `node` or the `web` and adjust accordingly. In this case it has be configured such that `node` targets use `@babel/preset-env` to transpile features for the current version of node, while the `web` target will transpile features back to ie 11 and Chrome 58. + ## Customized Loader `babel-loader` exposes a loader-builder utility that allows users to add custom handling diff --git a/src/index.js b/src/index.js index 2209bc65..51d93da3 100644 --- a/src/index.js +++ b/src/index.js @@ -158,7 +158,9 @@ async function loader(source, inputSourceMap, overrides) { ); } - const config = babel.loadPartialConfig(injectCaller(programmaticOptions)); + const config = babel.loadPartialConfig( + injectCaller(programmaticOptions, this.target), + ); if (config) { let options = config.options; if (overrides && overrides.config) { diff --git a/src/injectCaller.js b/src/injectCaller.js index 9ee10e03..d0e09750 100644 --- a/src/injectCaller.js +++ b/src/injectCaller.js @@ -1,6 +1,6 @@ const babel = require("@babel/core"); -module.exports = function injectCaller(opts) { +module.exports = function injectCaller(opts, target) { if (!supportsCallerOption()) return opts; return Object.assign({}, opts, { @@ -8,6 +8,10 @@ module.exports = function injectCaller(opts) { { name: "babel-loader", + // Provide plugins with insight into webpack target. + // https://github.com/babel/babel-loader/issues/787 + target, + // Webpack >= 2 supports ESM and dynamic import. supportsStaticESM: true, supportsDynamicImport: true,