Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: expose webpack target via babel caller #826

Merged
merged 2 commits into from Feb 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 31 additions & 0 deletions README.md
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" }
existentialism marked this conversation as resolved.
Show resolved Hide resolved
: { 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
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