From a47605c5eda56dc004d7236f4cd7f3e8139eed0c Mon Sep 17 00:00:00 2001 From: Dylan Piercey Date: Thu, 27 Feb 2020 08:52:47 -0800 Subject: [PATCH] feat: expose webpack target via babel caller --- README.md | 31 +++++++++++++++++++++++++++++++ src/index.js | 4 +++- src/injectCaller.js | 6 +++++- 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 16d362b5..3082449b 100644 --- a/README.md +++ b/README.md @@ -193,6 +193,37 @@ 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 in this case. + +For example, to change the environment targets passed to `@babel/preset-env` based on the webpack target: + +```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 + targets: api.caller(caller => caller && caller.target === "node") + ? { node: "current" } + : { chrome: "58", ie: "11" } + } + ] + ] + } +} +``` + ## 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,