You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

292 lines
9.9 KiB

4 years ago
  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. [![NPM Status](https://img.shields.io/npm/v/babel-loader.svg?style=flat)](https://www.npmjs.com/package/babel-loader)
  4. [![Build Status](https://travis-ci.org/babel/babel-loader.svg?branch=master)](https://travis-ci.org/babel/babel-loader)
  5. [![Build Status](https://ci.appveyor.com/api/projects/status/77y5mk6amwqt0q88/branch/master?svg=true)](https://ci.appveyor.com/project/babel/babel-loader/branch/master)
  6. [![codecov](https://codecov.io/gh/babel/babel-loader/branch/master/graph/badge.svg)](https://codecov.io/gh/babel/babel-loader)
  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. <h1 align="center">Babel Loader</h1>
  16. This package allows transpiling JavaScript files using [Babel](https://github.com/babel/babel) and [webpack](https://github.com/webpack/webpack).
  17. **Note**: Issues with the output should be reported on the Babel [Issues](https://github.com/babel/babel/issues) tracker.
  18. <h2 align="center">Install</h2>
  19. > webpack 4.x | babel-loader 8.x | babel 7.x
  20. ```bash
  21. npm install -D babel-loader @babel/core @babel/preset-env webpack
  22. ```
  23. <h2 align="center">Usage</h2>
  24. webpack documentation: [Loaders](https://webpack.js.org/loaders/)
  25. Within your webpack configuration object, you'll need to add the babel-loader to the list of modules, like so:
  26. ```javascript
  27. module: {
  28. rules: [
  29. {
  30. test: /\.m?js$/,
  31. exclude: /(node_modules|bower_components)/,
  32. use: {
  33. loader: 'babel-loader',
  34. options: {
  35. presets: ['@babel/preset-env']
  36. }
  37. }
  38. }
  39. ]
  40. }
  41. ```
  42. ### Options
  43. See the `babel` [options](https://babeljs.io/docs/en/options).
  44. You can pass options to the loader by using the [`options`](https://webpack.js.org/configuration/module/#rule-options-rule-query) property:
  45. ```javascript
  46. module: {
  47. rules: [
  48. {
  49. test: /\.m?js$/,
  50. exclude: /(node_modules|bower_components)/,
  51. use: {
  52. loader: 'babel-loader',
  53. options: {
  54. presets: ['@babel/preset-env'],
  55. plugins: ['@babel/plugin-proposal-object-rest-spread']
  56. }
  57. }
  58. }
  59. ]
  60. }
  61. ```
  62. This loader also supports the following loader-specific option:
  63. * `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.
  64. * `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.
  65. * `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.
  66. * `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 is you _must_ continue using `babel-loader` directly, but still want to customize.
  67. ## Troubleshooting
  68. ### babel-loader is slow!
  69. Make 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.
  70. To exclude `node_modules`, see the `exclude` option in the `loaders` config as documented above.
  71. You can also speed up babel-loader by as much as 2x by using the `cacheDirectory` option. This will cache transformations to the filesystem.
  72. ### Babel is injecting helpers into each file and bloating my code!
  73. Babel uses very small helpers for common functions such as `_extend`. By default, this will be added to every file that requires it.
  74. You can instead require the Babel runtime as a separate module to avoid the duplication.
  75. The following configuration disables automatic per-file runtime injection in Babel, requiring `@babel/plugin-transform-runtime` instead and making all helper references use it.
  76. See the [docs](https://babeljs.io/docs/plugins/transform-runtime/) for more information.
  77. **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`.
  78. ```javascript
  79. rules: [
  80. // the 'transform-runtime' plugin tells Babel to
  81. // require the runtime instead of inlining it.
  82. {
  83. test: /\.m?js$/,
  84. exclude: /(node_modules|bower_components)/,
  85. use: {
  86. loader: 'babel-loader',
  87. options: {
  88. presets: ['@babel/preset-env'],
  89. plugins: ['@babel/plugin-transform-runtime']
  90. }
  91. }
  92. }
  93. ]
  94. ```
  95. #### **NOTE**: transform-runtime & custom polyfills (e.g. Promise library)
  96. Since [@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:
  97. ```javascript
  98. // ...
  99. new webpack.ProvidePlugin({
  100. 'Promise': 'bluebird'
  101. }),
  102. // ...
  103. ```
  104. The following approach will not work either:
  105. ```javascript
  106. require('@babel/runtime/core-js/promise').default = require('bluebird');
  107. var promise = new Promise;
  108. ```
  109. which outputs to (using `runtime`):
  110. ```javascript
  111. 'use strict';
  112. var _Promise = require('@babel/runtime/core-js/promise')['default'];
  113. require('@babel/runtime/core-js/promise')['default'] = require('bluebird');
  114. var promise = new _Promise();
  115. ```
  116. The previous `Promise` library is referenced and used before it is overridden.
  117. One approach is to have a "bootstrap" step in your application that would first override the default globals before your application:
  118. ```javascript
  119. // bootstrap.js
  120. require('@babel/runtime/core-js/promise').default = require('bluebird');
  121. // ...
  122. require('./app');
  123. ```
  124. ### The Node.js API for `babel` has been moved to `babel-core`.
  125. If 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):
  126. ```javascript
  127. {
  128. test: /\.m?js$/,
  129. loader: 'babel',
  130. }
  131. ```
  132. webpack then tries to load the `babel` package instead of the `babel-loader`.
  133. To fix this, you should uninstall the npm package `babel`, as it is deprecated in Babel v6. (Instead, install `@babel/cli` or `@babel/core`.)
  134. In 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:
  135. ```javascript
  136. {
  137. test: /\.m?js$/,
  138. loader: 'babel-loader',
  139. }
  140. ```
  141. ## Customized Loader
  142. `babel-loader` exposes a loader-builder utility that allows users to add custom handling
  143. of Babel's configuration for each file that it processes.
  144. `.custom` accepts a callback that will be called with the loader's instance of
  145. `babel` so that tooling can ensure that it using exactly the same `@babel/core`
  146. instance as the loader itself.
  147. In cases where you want to customize without actually having a file to call `.custom`, you
  148. may also pass the `customize` option with a string pointing at a file that exports
  149. your `custom` callback function.
  150. ### Example
  151. ```js
  152. // Export from "./my-custom-loader.js" or whatever you want.
  153. module.exports = require("babel-loader").custom(babel => {
  154. function myPlugin() {
  155. return {
  156. visitor: {},
  157. };
  158. }
  159. return {
  160. // Passed the loader options.
  161. customOptions({ opt1, opt2, ...loader }) {
  162. return {
  163. // Pull out any custom options that the loader might have.
  164. custom: { opt1, opt2 },
  165. // Pass the options back with the two custom options removed.
  166. loader,
  167. };
  168. },
  169. // Passed Babel's 'PartialConfig' object.
  170. config(cfg) {
  171. if (cfg.hasFilesystemConfig()) {
  172. // Use the normal config
  173. return cfg.options;
  174. }
  175. return {
  176. ...cfg.options,
  177. plugins: [
  178. ...(cfg.options.plugins || []),
  179. // Include a custom plugin in the options.
  180. myPlugin,
  181. ],
  182. };
  183. },
  184. result(result) {
  185. return {
  186. ...result,
  187. code: result.code + "\n// Generated by some custom loader",
  188. };
  189. },
  190. };
  191. });
  192. ```
  193. ```js
  194. // And in your Webpack config
  195. module.exports = {
  196. // ..
  197. module: {
  198. rules: [{
  199. // ...
  200. loader: path.join(__dirname, 'my-custom-loader.js'),
  201. // ...
  202. }]
  203. }
  204. };
  205. ```
  206. ### `customOptions(options: Object): { custom: Object, loader: Object }`
  207. Given the loader's options, split custom options out of `babel-loader`'s
  208. options.
  209. ### `config(cfg: PartialConfig): Object`
  210. Given Babel's `PartialConfig` object, return the `options` object that should
  211. be passed to `babel.transform`.
  212. ### `result(result: Result): Result`
  213. Given Babel's result object, allow loaders to make additional tweaks to it.
  214. ## License
  215. [MIT](https://couto.mit-license.org/)