Skip to content

Commit

Permalink
feat: expose webpack target via babel caller
Browse files Browse the repository at this point in the history
  • Loading branch information
DylanPiercey committed Feb 27, 2020
1 parent b568420 commit d5483a1
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
32 changes: 32 additions & 0 deletions README.md
Expand Up @@ -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 in 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 been 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
Expand Down
4 changes: 3 additions & 1 deletion src/index.js
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
@@ -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 d5483a1

Please sign in to comment.