UNPKG

11.1 kBMarkdownView Raw
1> This README is for babel-loader v8 + Babel v7
2> Check the [7.x branch](https://github.com/babel/babel-loader/tree/7.x) for docs with Babel v6
3
4[![NPM Status](https://img.shields.io/npm/v/babel-loader.svg?style=flat)](https://www.npmjs.com/package/babel-loader)
5[![Build Status](https://travis-ci.org/babel/babel-loader.svg?branch=master)](https://travis-ci.org/babel/babel-loader)
6[![Build Status](https://ci.appveyor.com/api/projects/status/77y5mk6amwqt0q88/branch/master?svg=true)](https://ci.appveyor.com/project/babel/babel-loader/branch/master)
7[![codecov](https://codecov.io/gh/babel/babel-loader/branch/master/graph/badge.svg)](https://codecov.io/gh/babel/babel-loader)
8
9<div align="center">
10 <a href="https://github.com/babel/babel">
11 <img src="https://rawgit.com/babel/logo/master/babel.svg" alt="Babel logo" width="200" height="200">
12 </a>
13 <a href="https://github.com/webpack/webpack">
14 <img src="https://webpack.js.org/assets/icon-square-big.svg" alt="webpack logo" width="200" height="200">
15 </a>
16</div>
17
18<h1 align="center">Babel Loader</h1>
19
20This package allows transpiling JavaScript files using [Babel](https://github.com/babel/babel) and [webpack](https://github.com/webpack/webpack).
21
22**Note**: Issues with the output should be reported on the Babel [Issues](https://github.com/babel/babel/issues) tracker.
23
24<h2 align="center">Install</h2>
25
26> webpack 4.x | babel-loader 8.x | babel 7.x
27
28```bash
29npm install -D babel-loader @babel/core @babel/preset-env webpack
30```
31
32<h2 align="center">Usage</h2>
33
34webpack documentation: [Loaders](https://webpack.js.org/loaders/)
35
36Within your webpack configuration object, you'll need to add the babel-loader to the list of modules, like so:
37
38```javascript
39module: {
40 rules: [
41 {
42 test: /\.m?js$/,
43 exclude: /(node_modules|bower_components)/,
44 use: {
45 loader: 'babel-loader',
46 options: {
47 presets: ['@babel/preset-env']
48 }
49 }
50 }
51 ]
52}
53```
54
55### Options
56
57See the `babel` [options](https://babeljs.io/docs/en/options).
58
59You can pass options to the loader by using the [`options`](https://webpack.js.org/configuration/module/#rule-options-rule-query) property:
60
61```javascript
62module: {
63 rules: [
64 {
65 test: /\.m?js$/,
66 exclude: /(node_modules|bower_components)/,
67 use: {
68 loader: 'babel-loader',
69 options: {
70 presets: ['@babel/preset-env'],
71 plugins: ['@babel/plugin-proposal-object-rest-spread']
72 }
73 }
74 }
75 ]
76}
77```
78
79This loader also supports the following loader-specific option:
80
81* `cacheDirectory`: Default `false`. When set, the given directory will be used to cache the results of the loader. Future webpack builds will attempt to read from the cache to avoid needing to run the potentially expensive Babel recompilation process on each run. If the value is set to `true` in options (`{cacheDirectory: true}`), the loader will use the default cache directory in `node_modules/.cache/babel-loader` or fallback to the default OS temporary file directory if no `node_modules` folder could be found in any root directory.
82
83* `cacheIdentifier`: Default is a string composed by the `@babel/core`'s version, the `babel-loader`'s version, the contents of `.babelrc` file if it exists, and the value of the environment variable `BABEL_ENV` with a fallback to the `NODE_ENV` environment variable. This can be set to a custom value to force cache busting if the identifier changes.
84
85* `cacheCompression`: Default `true`. When set, each Babel transform output will be compressed with Gzip. If you want to opt-out of cache compression, set it to `false` -- your project may benefit from this if it transpiles thousands of files.
86
87* `customize`: Default `null`. The path of a module that exports a `custom` callback [like the one that you'd pass to `.custom()`](#customized-loader). Since you already have to make a new file to use this, it is recommended that you instead use `.custom` to create a wrapper loader. Only use this if you _must_ continue using `babel-loader` directly, but still want to customize.
88
89## Troubleshooting
90
91### babel-loader is slow!
92
93Make sure you are transforming as few files as possible. Because you are probably matching `/\.m?js$/`, you might be transforming the `node_modules` folder or other unwanted source.
94
95To exclude `node_modules`, see the `exclude` option in the `loaders` config as documented above.
96
97You can also speed up babel-loader by as much as 2x by using the `cacheDirectory` option. This will cache transformations to the filesystem.
98
99### Babel is injecting helpers into each file and bloating my code!
100
101Babel uses very small helpers for common functions such as `_extend`. By default, this will be added to every file that requires it.
102
103You can instead require the Babel runtime as a separate module to avoid the duplication.
104
105The following configuration disables automatic per-file runtime injection in Babel, requiring `@babel/plugin-transform-runtime` instead and making all helper references use it.
106
107See the [docs](https://babeljs.io/docs/plugins/transform-runtime/) for more information.
108
109**NOTE**: You must run `npm install -D @babel/plugin-transform-runtime` to include this in your project and `@babel/runtime` itself as a dependency with `npm install @babel/runtime`.
110
111```javascript
112rules: [
113 // the 'transform-runtime' plugin tells Babel to
114 // require the runtime instead of inlining it.
115 {
116 test: /\.m?js$/,
117 exclude: /(node_modules|bower_components)/,
118 use: {
119 loader: 'babel-loader',
120 options: {
121 presets: ['@babel/preset-env'],
122 plugins: ['@babel/plugin-transform-runtime']
123 }
124 }
125 }
126]
127```
128
129#### **NOTE**: transform-runtime & custom polyfills (e.g. Promise library)
130
131Since [@babel/plugin-transform-runtime](https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-runtime) includes a polyfill that includes a custom [regenerator-runtime](https://github.com/facebook/regenerator/blob/master/packages/regenerator-runtime/runtime.js) and [core-js](https://github.com/zloirock/core-js), the following usual shimming method using `webpack.ProvidePlugin` will not work:
132
133```javascript
134// ...
135 new webpack.ProvidePlugin({
136 'Promise': 'bluebird'
137 }),
138// ...
139```
140
141The following approach will not work either:
142
143```javascript
144require('@babel/runtime/core-js/promise').default = require('bluebird');
145
146var promise = new Promise;
147```
148
149which outputs to (using `runtime`):
150
151```javascript
152'use strict';
153
154var _Promise = require('@babel/runtime/core-js/promise')['default'];
155
156require('@babel/runtime/core-js/promise')['default'] = require('bluebird');
157
158var promise = new _Promise();
159```
160
161The previous `Promise` library is referenced and used before it is overridden.
162
163One approach is to have a "bootstrap" step in your application that would first override the default globals before your application:
164
165```javascript
166// bootstrap.js
167
168require('@babel/runtime/core-js/promise').default = require('bluebird');
169
170// ...
171
172require('./app');
173```
174
175### The Node.js API for `babel` has been moved to `babel-core`.
176
177If you receive this message, it means that you have the npm package `babel` installed and are using the short notation of the loader in the webpack config (which is not valid anymore as of webpack 2.x):
178```javascript
179 {
180 test: /\.m?js$/,
181 loader: 'babel',
182 }
183```
184
185webpack then tries to load the `babel` package instead of the `babel-loader`.
186
187To fix this, you should uninstall the npm package `babel`, as it is deprecated in Babel v6. (Instead, install `@babel/cli` or `@babel/core`.)
188In the case one of your dependencies is installing `babel` and you cannot uninstall it yourself, use the complete name of the loader in the webpack config:
189```javascript
190 {
191 test: /\.m?js$/,
192 loader: 'babel-loader',
193 }
194```
195
196## Customize config based on webpack target
197
198Webpack 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.
199
200For example, to change the environment targets passed to `@babel/preset-env` based on the webpack target:
201
202```javascript
203// babel.config.js
204
205module.exports = api => {
206 return {
207 plugins: [
208 "@babel/plugin-proposal-nullish-coalescing-operator",
209 "@babel/plugin-proposal-optional-chaining"
210 ],
211 presets: [
212 [
213 "@babel/preset-env",
214 {
215 useBuiltIns: "entry",
216 // caller.target will be the same as the target option from webpack
217 targets: api.caller(caller => caller && caller.target === "node")
218 ? { node: "current" }
219 : { chrome: "58", ie: "11" }
220 }
221 ]
222 ]
223 }
224}
225```
226
227## Customized Loader
228
229`babel-loader` exposes a loader-builder utility that allows users to add custom handling
230of Babel's configuration for each file that it processes.
231
232`.custom` accepts a callback that will be called with the loader's instance of
233`babel` so that tooling can ensure that it using exactly the same `@babel/core`
234instance as the loader itself.
235
236In cases where you want to customize without actually having a file to call `.custom`, you
237may also pass the `customize` option with a string pointing at a file that exports
238your `custom` callback function.
239
240### Example
241
242```js
243// Export from "./my-custom-loader.js" or whatever you want.
244module.exports = require("babel-loader").custom(babel => {
245 function myPlugin() {
246 return {
247 visitor: {},
248 };
249 }
250
251 return {
252 // Passed the loader options.
253 customOptions({ opt1, opt2, ...loader }) {
254 return {
255 // Pull out any custom options that the loader might have.
256 custom: { opt1, opt2 },
257
258 // Pass the options back with the two custom options removed.
259 loader,
260 };
261 },
262
263 // Passed Babel's 'PartialConfig' object.
264 config(cfg) {
265 if (cfg.hasFilesystemConfig()) {
266 // Use the normal config
267 return cfg.options;
268 }
269
270 return {
271 ...cfg.options,
272 plugins: [
273 ...(cfg.options.plugins || []),
274
275 // Include a custom plugin in the options.
276 myPlugin,
277 ],
278 };
279 },
280
281 result(result) {
282 return {
283 ...result,
284 code: result.code + "\n// Generated by some custom loader",
285 };
286 },
287 };
288});
289```
290
291```js
292// And in your Webpack config
293module.exports = {
294 // ..
295 module: {
296 rules: [{
297 // ...
298 loader: path.join(__dirname, 'my-custom-loader.js'),
299 // ...
300 }]
301 }
302};
303```
304
305### `customOptions(options: Object): { custom: Object, loader: Object }`
306
307Given the loader's options, split custom options out of `babel-loader`'s
308options.
309
310
311### `config(cfg: PartialConfig): Object`
312
313Given Babel's `PartialConfig` object, return the `options` object that should
314be passed to `babel.transform`.
315
316
317### `result(result: Result): Result`
318
319Given Babel's result object, allow loaders to make additional tweaks to it.
320
321
322## License
323[MIT](https://couto.mit-license.org/)