|
1 |
| -# transform-async-modules-webpack-plugin |
| 1 | +# Transform Async Modules Webpack Plugin |
2 | 2 |
|
3 |
| -A Webpack plugin to transpile async module output using Babel |
| 3 | +## What it solves |
| 4 | + |
| 5 | +[Webpack](https://webpack.js.org) converts uses of top level `await` expressions into modules that are wrapped in an `async function`. Since transpilation usually happens when modules are loaded, the resulting chunks still contain these wrappers. Thus they are not compatible with legacy browsers or other environments that do not support ES2017 or later. |
| 6 | + |
| 7 | +## How it works |
| 8 | + |
| 9 | +The plugin works by transforming async modules using [`@babel/preset-env`](https://babeljs.io/docs/babel-preset-env) right before they are ready to be written to a chunk. It is expected that modules are already transpiled using [`babel-loader`](https://www.npmjs.com/package/babel-loader), so the primary transformations occurring are simply to the `async function`: |
| 10 | + |
| 11 | +1. [`@babel/plugin-transform-async-to-generator`](https://babeljs.io/docs/babel-plugin-transform-async-to-generator) to convert to a generator function, and |
| 12 | +2. [`@babel/plugin-transform-regenerator`](https://babeljs.io/docs/babel-plugin-transform-regenerator) to convert the ES2015 generator |
| 13 | + |
| 14 | +Whether or not each transformation happens will depend on the target browsers passed to the plugin. |
| 15 | + |
| 16 | +Any `devTool` (source maps) option used in Webpack is supported. This includes "eval" options as the transform occurs right before the modules are wrapped in `eval()`. |
| 17 | + |
| 18 | +## Usage |
| 19 | + |
| 20 | +Install the package from NPM and require or import it for your Webpack configuration: |
| 21 | + |
| 22 | +```js |
| 23 | +const TransformAsyncModulesPlugin = require("transform-async-modules-webpack-plugin"); |
| 24 | +``` |
| 25 | + |
| 26 | +or |
| 27 | + |
| 28 | +```js |
| 29 | +import TransformAsyncModulesPlugin from "transform-async-modules-webpack-plugin"; |
| 30 | +``` |
| 31 | + |
| 32 | +Then add an instance to the plugins array: |
| 33 | + |
| 34 | +```js |
| 35 | +export default { |
| 36 | + // ... other Webpack config |
| 37 | + plugins: [ |
| 38 | + // ... other plugins |
| 39 | + new TransformAsyncModulesPlugin(options), |
| 40 | + ], |
| 41 | +}; |
| 42 | +``` |
| 43 | + |
| 44 | +## Options |
| 45 | + |
| 46 | +The options passed to the plugin are optional. Properties are a subset of [Babel options to specify targets](https://babeljs.io/docs/options#output-targets), and are passed directly to the transform function. |
| 47 | + |
| 48 | +```ts |
| 49 | +interface TransformAsyncModulesPluginOptions { |
| 50 | + targets?: Targets; // see Babel docs for details |
| 51 | + browserslistConfigFile?: boolean; |
| 52 | + browserslistEnv?: string; |
| 53 | +} |
| 54 | +``` |
0 commit comments