source: imaps-frontend/node_modules/babel-loader/README.md

main
Last change on this file was 79a0317, checked in by stefan toskovski <stefantoska84@…>, 4 days ago

F4 Finalna Verzija

  • Property mode set to 100644
File size: 13.8 KB
Line 
1> This README is for babel-loader v8/v9 with Babel v7
2> If you are using legacy Babel v6, see the [7.x branch](https://github.com/babel/babel-loader/tree/7.x) docs
3
4[![NPM Status](https://img.shields.io/npm/v/babel-loader.svg?style=flat)](https://www.npmjs.com/package/babel-loader)
5[![codecov](https://codecov.io/gh/babel/babel-loader/branch/main/graph/badge.svg)](https://codecov.io/gh/babel/babel-loader)
6
7<div align="center">
8 <a href="https://github.com/babel/babel">
9 <img src="https://rawgit.com/babel/logo/master/babel.svg" alt="Babel logo" width="200" height="200">
10 </a>
11 <a href="https://github.com/webpack/webpack">
12 <img src="https://webpack.js.org/assets/icon-square-big.svg" alt="webpack logo" width="200" height="200">
13 </a>
14</div>
15
16<h1 align="center">Babel Loader</h1>
17
18This package allows transpiling JavaScript files using [Babel](https://github.com/babel/babel) and [webpack](https://github.com/webpack/webpack).
19
20**Note**: Issues with the output should be reported on the Babel [Issues](https://github.com/babel/babel/issues) tracker.
21
22<h2 align="center">Install</h2>
23
24> | babel-loader | supported webpack versions | supported Babel versions | supported Node.js versions |
25> |:-:|:-:|:-:|:-:|
26> | 8.x | 4.x or 5.x | 7.x | >= 8.9 |
27> | 9.x | 5.x | ^7.12.0 | >= 14.15.0 |
28
29
30```bash
31npm install -D babel-loader @babel/core @babel/preset-env webpack
32```
33
34<h2 align="center">Usage</h2>
35
36webpack documentation: [Loaders](https://webpack.js.org/loaders/)
37
38Within your webpack configuration object, you'll need to add the babel-loader to the list of modules, like so:
39
40```javascript
41module: {
42 rules: [
43 {
44 test: /\.(?:js|mjs|cjs)$/,
45 exclude: /node_modules/,
46 use: {
47 loader: 'babel-loader',
48 options: {
49 presets: [
50 ['@babel/preset-env', { targets: "defaults" }]
51 ]
52 }
53 }
54 }
55 ]
56}
57```
58
59### Options
60
61See the `babel` [options](https://babeljs.io/docs/en/options).
62
63You can pass options to the loader by using the [`options`](https://webpack.js.org/configuration/module/#ruleoptions--rulequery) property:
64
65```javascript
66module: {
67 rules: [
68 {
69 test: /\.(?:js|mjs|cjs)$/,
70 exclude: /node_modules/,
71 use: {
72 loader: 'babel-loader',
73 options: {
74 presets: [
75 ['@babel/preset-env', { targets: "defaults" }]
76 ],
77 plugins: ['@babel/plugin-proposal-class-properties']
78 }
79 }
80 }
81 ]
82}
83```
84
85The `options` passed here will be [merged](https://babeljs.io/docs/configuration#how-babel-merges-config-items) with Babel config files, e.g. `babel.config.js` or `.babelrc`.
86
87This loader also supports the following loader-specific option:
88
89* `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.
90
91* `cacheIdentifier`: Default is a string composed by
92 - the `@babel/core`'s version and the `babel-loader`'s version
93 - the [merged](https://babeljs.io/docs/configuration#how-babel-merges-config-items) [Babel config](https://babeljs.io/docs/config-files), including options passed to `babel-loader` and the contents of `babel.config.js` or `.babelrc` file if they exist
94 - the value of the environment variable `BABEL_ENV` with a fallback to the `NODE_ENV` environment variable.
95 This can be set to a custom value to force cache busting if the identifier changes.
96
97* `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.
98
99* `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.
100
101* `metadataSubscribers`: Default `[]`. Takes an array of context function names. E.g. if you passed ['myMetadataPlugin'], you'd assign a subscriber function to `context.myMetadataPlugin` within your webpack plugin's hooks & that function will be called with `metadata`.
102
103## Troubleshooting
104
105### babel-loader is slow!
106
107Make 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.
108
109To exclude `node_modules`, see the `exclude` option in the `loaders` config as documented above.
110
111You can also speed up babel-loader by as much as 2x by using the `cacheDirectory` option. This will cache transformations to the filesystem.
112
113### Some files in my node_modules are not transpiled for IE 11
114
115Although we typically recommend not compiling `node_modules`, you may need to when using libraries that do not support IE 11 or any legacy targets.
116
117For this, you can either use a combination of `test` and `not`, or [pass a function](https://webpack.js.org/configuration/module/#condition) to your `exclude` option. You can also use negative lookahead regex as suggested [here](https://github.com/webpack/webpack/issues/2031#issuecomment-294706065).
118
119```javascript
120{
121 test: /\.(?:js|mjs|cjs)$/,
122 exclude: {
123 and: [/node_modules/], // Exclude libraries in node_modules ...
124 not: [
125 // Except for a few of them that needs to be transpiled because they use modern syntax
126 /unfetch/,
127 /d3-array|d3-scale/,
128 /@hapi[\\/]joi-date/,
129 ]
130 },
131 use: {
132 loader: 'babel-loader',
133 options: {
134 presets: [
135 ['@babel/preset-env', { targets: "ie 11" }]
136 ]
137 }
138 }
139 }
140```
141
142### Babel is injecting helpers into each file and bloating my code!
143
144Babel uses very small helpers for common functions such as `_extend`. By default, this will be added to every file that requires it.
145
146You can instead require the Babel runtime as a separate module to avoid the duplication.
147
148The following configuration disables automatic per-file runtime injection in Babel, requiring `@babel/plugin-transform-runtime` instead and making all helper references use it.
149
150See the [docs](https://babeljs.io/docs/plugins/transform-runtime/) for more information.
151
152**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`.
153
154```javascript
155rules: [
156 // the 'transform-runtime' plugin tells Babel to
157 // require the runtime instead of inlining it.
158 {
159 test: /\.(?:js|mjs|cjs)$/,
160 exclude: /node_modules/,
161 use: {
162 loader: 'babel-loader',
163 options: {
164 presets: [
165 ['@babel/preset-env', { targets: "defaults" }]
166 ],
167 plugins: ['@babel/plugin-transform-runtime']
168 }
169 }
170 }
171]
172```
173
174#### **NOTE**: transform-runtime & custom polyfills (e.g. Promise library)
175
176Since [@babel/plugin-transform-runtime](https://github.com/babel/babel/tree/main/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:
177
178```javascript
179// ...
180 new webpack.ProvidePlugin({
181 'Promise': 'bluebird'
182 }),
183// ...
184```
185
186The following approach will not work either:
187
188```javascript
189require('@babel/runtime/core-js/promise').default = require('bluebird');
190
191var promise = new Promise;
192```
193
194which outputs to (using `runtime`):
195
196```javascript
197'use strict';
198
199var _Promise = require('@babel/runtime/core-js/promise')['default'];
200
201require('@babel/runtime/core-js/promise')['default'] = require('bluebird');
202
203var promise = new _Promise();
204```
205
206The previous `Promise` library is referenced and used before it is overridden.
207
208One approach is to have a "bootstrap" step in your application that would first override the default globals before your application:
209
210```javascript
211// bootstrap.js
212
213require('@babel/runtime/core-js/promise').default = require('bluebird');
214
215// ...
216
217require('./app');
218```
219
220### The Node.js API for `babel` has been moved to `babel-core`.
221
222If 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):
223```javascript
224 {
225 test: /\.(?:js|mjs|cjs)$/,
226 loader: 'babel',
227 }
228```
229
230webpack then tries to load the `babel` package instead of the `babel-loader`.
231
232To fix this, you should uninstall the npm package `babel`, as it is deprecated in Babel v6. (Instead, install `@babel/cli` or `@babel/core`.)
233In 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:
234```javascript
235 {
236 test: /\.(?:js|mjs|cjs)$/,
237 loader: 'babel-loader',
238 }
239```
240
241### Exclude libraries that should not be transpiled
242
243`core-js` and `webpack/buildin` will cause errors if they are transpiled by Babel.
244
245You will need to exclude them form `babel-loader`.
246
247```js
248{
249 "loader": "babel-loader",
250 "options": {
251 "exclude": [
252 // \\ for Windows, / for macOS and Linux
253 /node_modules[\\/]core-js/,
254 /node_modules[\\/]webpack[\\/]buildin/,
255 ],
256 "presets": [
257 "@babel/preset-env"
258 ]
259 }
260}
261```
262
263### Top level function (IIFE) is still arrow (on Webpack 5)
264
265That function is injected by Webpack itself _after_ running `babel-loader`. By default Webpack asumes that your target environment supports some ES2015 features, but you can overwrite this behavior using the `output.environment` Webpack option ([documentation](https://webpack.js.org/configuration/output/#outputenvironment)).
266
267To avoid the top-level arrow function, you can use `output.environment.arrowFunction`:
268
269```js
270// webpack.config.js
271module.exports = {
272 // ...
273 output: {
274 // ...
275 environment: {
276 // ...
277 arrowFunction: false, // <-- this line does the trick
278 },
279 },
280};
281```
282
283## Customize config based on webpack target
284
285Webpack 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.
286
287For example, to change the environment targets passed to `@babel/preset-env` based on the webpack target:
288
289```javascript
290// babel.config.js
291
292module.exports = api => {
293 return {
294 plugins: [
295 "@babel/plugin-proposal-nullish-coalescing-operator",
296 "@babel/plugin-proposal-optional-chaining"
297 ],
298 presets: [
299 [
300 "@babel/preset-env",
301 {
302 useBuiltIns: "entry",
303 // caller.target will be the same as the target option from webpack
304 targets: api.caller(caller => caller && caller.target === "node")
305 ? { node: "current" }
306 : { chrome: "58", ie: "11" }
307 }
308 ]
309 ]
310 }
311}
312```
313
314## Customized Loader
315
316`babel-loader` exposes a loader-builder utility that allows users to add custom handling
317of Babel's configuration for each file that it processes.
318
319`.custom` accepts a callback that will be called with the loader's instance of
320`babel` so that tooling can ensure that it using exactly the same `@babel/core`
321instance as the loader itself.
322
323In cases where you want to customize without actually having a file to call `.custom`, you
324may also pass the `customize` option with a string pointing at a file that exports
325your `custom` callback function.
326
327### Example
328
329```js
330// Export from "./my-custom-loader.js" or whatever you want.
331module.exports = require("babel-loader").custom(babel => {
332 // Extract the custom options in the custom plugin
333 function myPlugin(api, { opt1, opt2 }) {
334 return {
335 visitor: {},
336 };
337 }
338
339 return {
340 // Passed the loader options.
341 customOptions({ opt1, opt2, ...loader }) {
342 return {
343 // Pull out any custom options that the loader might have.
344 custom: { opt1, opt2 },
345
346 // Pass the options back with the two custom options removed.
347 loader,
348 };
349 },
350
351 // Passed Babel's 'PartialConfig' object.
352 config(cfg, { customOptions }) {
353 if (cfg.hasFilesystemConfig()) {
354 // Use the normal config
355 return cfg.options;
356 }
357
358 return {
359 ...cfg.options,
360 plugins: [
361 ...(cfg.options.plugins || []),
362
363 // Include a custom plugin in the options and passing it the customOptions object.
364 [myPlugin, customOptions],
365 ],
366 };
367 },
368
369 result(result) {
370 return {
371 ...result,
372 code: result.code + "\n// Generated by some custom loader",
373 };
374 },
375 };
376});
377```
378
379```js
380// And in your Webpack config
381module.exports = {
382 // ..
383 module: {
384 rules: [{
385 // ...
386 loader: path.join(__dirname, 'my-custom-loader.js'),
387 // ...
388 }]
389 }
390};
391```
392
393### `customOptions(options: Object): { custom: Object, loader: Object }`
394
395Given the loader's options, split custom options out of `babel-loader`'s
396options.
397
398
399### `config(cfg: PartialConfig, options: { source, customOptions }): Object`
400
401Given Babel's `PartialConfig` object, return the `options` object that should
402be passed to `babel.transform`.
403
404
405### `result(result: Result): Result`
406
407Given Babel's result object, allow loaders to make additional tweaks to it.
408
409
410## License
411[MIT](https://couto.mit-license.org/)
Note: See TracBrowser for help on using the repository browser.