From 13a82386473986517a6e9dcfb1a7b75b47379d64 Mon Sep 17 00:00:00 2001 From: Dylan Piercey Date: Thu, 27 Feb 2020 21:36:41 -0800 Subject: [PATCH] feat: expose webpack target via babel caller (#826) Co-authored-by: Brian Ng --- 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..43162e80 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 based on webpack target + +Webpack supports bundling multiple [targets](https://webpack.js.org/concepts/targets/). For cases where you may want different Babel configurations for each target (like `web` _and_ `node`), this loader provides a `target` property via Babel's [caller](https://babeljs.io/docs/en/config-files#apicallercb) API. + +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,