Skip to content

Commit

Permalink
feat: expose webpack target via babel caller (#826)
Browse files Browse the repository at this point in the history
Co-authored-by: Brian Ng <bng412@gmail.com>
  • Loading branch information
DylanPiercey and existentialism authored Feb 28, 2020
1 parent b568420 commit 13a8238
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
6 changes: 5 additions & 1 deletion src/injectCaller.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
const babel = require("@babel/core");

module.exports = function injectCaller(opts) {
module.exports = function injectCaller(opts, target) {
if (!supportsCallerOption()) return opts;

return Object.assign({}, opts, {
caller: Object.assign(
{
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,
Expand Down

0 comments on commit 13a8238

Please sign in to comment.