Installations
npm install babel-loader
Developer
babel
Developer Guide
Module System
CommonJS
Min. Node Version
>= 14.15.0
Typescript Support
No
Node Version
NPM Version
Statistics
4,828 Stars
618 Commits
451 Forks
78 Watching
29 Branches
133 Contributors
Updated on 26 Nov 2024
Bundle Size
165.76 kB
Minified
46.35 kB
Minified + Gzipped
Languages
JavaScript (100%)
Total Downloads
Cumulative downloads
Total Downloads
4,038,705,566
Last day
-4.8%
3,680,544
Compared to previous day
Last week
2.8%
19,408,942
Compared to previous week
Last month
12.1%
80,302,529
Compared to previous month
Last year
-4%
888,243,556
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
This README is for babel-loader v8/v9 with Babel v7 If you are using legacy Babel v6, see the 7.x branch docs
Babel Loader
This package allows transpiling JavaScript files using Babel and webpack.
Note: Issues with the output should be reported on the Babel Issues tracker.
Install
babel-loader supported webpack versions supported Babel versions supported Node.js versions 8.x 4.x or 5.x 7.x >= 8.9 9.x 5.x ^7.12.0 >= 14.15.0
1npm install -D babel-loader @babel/core @babel/preset-env webpack
Usage
webpack documentation: Loaders
Within your webpack configuration object, you'll need to add the babel-loader to the list of modules, like so:
1module: { 2 rules: [ 3 { 4 test: /\.(?:js|mjs|cjs)$/, 5 exclude: /node_modules/, 6 use: { 7 loader: 'babel-loader', 8 options: { 9 targets: "defaults", 10 presets: [ 11 ['@babel/preset-env'] 12 ] 13 } 14 } 15 } 16 ] 17}
Options
See the babel
options.
You can pass options to the loader by using the options
property:
1module: { 2 rules: [ 3 { 4 test: /\.(?:js|mjs|cjs)$/, 5 exclude: /node_modules/, 6 use: { 7 loader: 'babel-loader', 8 options: { 9 targets: "defaults", 10 presets: [ 11 ['@babel/preset-env'] 12 ], 13 plugins: ['@babel/plugin-proposal-decorators', { version: "2023-11" }] 14 } 15 } 16 } 17 ] 18}
The options
passed here will be merged with Babel config files, e.g. babel.config.js
or .babelrc
.
This loader also supports the following loader-specific option:
-
cacheDirectory
: Defaultfalse
. 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 totrue
in options ({cacheDirectory: true}
), the loader will use the default cache directory innode_modules/.cache/babel-loader
or fallback to the default OS temporary file directory if nonode_modules
folder could be found in any root directory. -
cacheIdentifier
: Default is a string composed by the@babel/core
's version and thebabel-loader
's version. The final cache id will be determined by the input file path, the merged Babel config viaBabel.loadPartialConfigAsync
and thecacheIdentifier
. The merged Babel config will be determined by thebabel.config.js
or.babelrc
file if they exist, or the value of the environment variableBABEL_ENV
andNODE_ENV
.cacheIdentifier
can be set to a custom value to force cache busting if the identifier changes. -
cacheCompression
: Defaulttrue
. When set, each Babel transform output will be compressed with Gzip. If you want to opt-out of cache compression, set it tofalse
-- your project may benefit from this if it transpiles thousands of files. -
customize
: Defaultnull
. The path of a module that exports acustom
callback like the one that you'd pass to.custom()
. 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 usingbabel-loader
directly, but still want to customize. -
metadataSubscribers
: Default[]
. Takes an array of context function names. E.g. if you passed ['myMetadataPlugin'], you'd assign a subscriber function tocontext.myMetadataPlugin
within your webpack plugin's hooks & that function will be called withmetadata
. See./test/metadata.test.js
for an example.
Troubleshooting
Enable debug mode logging
Specify the webpack option stats.loggingDebug
to output verbose debug logs.
1// webpack.config.js 2module.exports = { 3 // ... 4 stats: { 5 loggingDebug: ["babel-loader"] 6 } 7}
babel-loader is slow!
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.
To exclude node_modules
, see the exclude
option in the loaders
config as documented above.
You can also speed up babel-loader by as much as 2x by using the cacheDirectory
option. This will cache transformations to the filesystem.
Some files in my node_modules are not transpiled for IE 11
Although we typically recommend not compiling node_modules
, you may need to when using libraries that do not support IE 11 or any legacy targets.
For this, you can either use a combination of test
and not
, or pass a function to your exclude
option. You can also use negative lookahead regex as suggested here.
1{ 2 test: /\.(?:js|mjs|cjs)$/, 3 exclude: { 4 and: [/node_modules/], // Exclude libraries in node_modules ... 5 not: [ 6 // Except for a few of them that needs to be transpiled because they use modern syntax 7 /unfetch/, 8 /d3-array|d3-scale/, 9 /@hapi[\\/]joi-date/, 10 ] 11 }, 12 use: { 13 loader: 'babel-loader', 14 options: { 15 presets: [ 16 ['@babel/preset-env', { targets: "ie 11" }] 17 ] 18 } 19 } 20 }
Babel is injecting helpers into each file and bloating my code!
Babel uses very small helpers for common functions such as _extend
. By default, this will be added to every file that requires it.
You can instead require the Babel runtime as a separate module to avoid the duplication.
The following configuration disables automatic per-file runtime injection in Babel, requiring @babel/plugin-transform-runtime
instead and making all helper references use it.
See the docs for more information.
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
.
1rules: [ 2 // the 'transform-runtime' plugin tells Babel to 3 // require the runtime instead of inlining it. 4 { 5 test: /\.(?:js|mjs|cjs)$/, 6 exclude: /node_modules/, 7 use: { 8 loader: 'babel-loader', 9 options: { 10 presets: [ 11 ['@babel/preset-env', { targets: "defaults" }] 12 ], 13 plugins: ['@babel/plugin-transform-runtime'] 14 } 15 } 16 } 17]
NOTE: transform-runtime & custom polyfills (e.g. Promise library)
Since @babel/plugin-transform-runtime includes a polyfill that includes a custom regenerator-runtime and core-js, the following usual shimming method using webpack.ProvidePlugin
will not work:
1// ... 2 new webpack.ProvidePlugin({ 3 'Promise': 'bluebird' 4 }), 5// ...
The following approach will not work either:
1require('@babel/runtime/core-js/promise').default = require('bluebird'); 2 3var promise = new Promise;
which outputs to (using runtime
):
1'use strict'; 2 3var _Promise = require('@babel/runtime/core-js/promise')['default']; 4 5require('@babel/runtime/core-js/promise')['default'] = require('bluebird'); 6 7var promise = new _Promise();
The previous Promise
library is referenced and used before it is overridden.
One approach is to have a "bootstrap" step in your application that would first override the default globals before your application:
1// bootstrap.js 2 3require('@babel/runtime/core-js/promise').default = require('bluebird'); 4 5// ... 6 7require('./app');
The Node.js API for babel
has been moved to babel-core
.
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):
1 { 2 test: /\.(?:js|mjs|cjs)$/, 3 loader: 'babel', 4 }
webpack then tries to load the babel
package instead of the babel-loader
.
To fix this, you should uninstall the npm package babel
, as it is deprecated in Babel v6. (Instead, install @babel/cli
or @babel/core
.)
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:
1 { 2 test: /\.(?:js|mjs|cjs)$/, 3 loader: 'babel-loader', 4 }
Exclude libraries that should not be transpiled
core-js
and webpack/buildin
will cause errors if they are transpiled by Babel.
You will need to exclude them form babel-loader
.
1{ 2 "loader": "babel-loader", 3 "options": { 4 "exclude": [ 5 // \\ for Windows, / for macOS and Linux 6 /node_modules[\\/]core-js/, 7 /node_modules[\\/]webpack[\\/]buildin/, 8 ], 9 "presets": [ 10 "@babel/preset-env" 11 ] 12 } 13}
Top level function (IIFE) is still arrow (on Webpack 5)
That 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).
To avoid the top-level arrow function, you can use output.environment.arrowFunction
:
1// webpack.config.js 2module.exports = { 3 // ... 4 output: { 5 // ... 6 environment: { 7 // ... 8 arrowFunction: false, // <-- this line does the trick 9 }, 10 }, 11};
Customize config based on webpack target
Webpack supports bundling multiple 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 API.
For example, to change the environment targets passed to @babel/preset-env
based on the webpack target:
1// babel.config.js 2 3module.exports = api => { 4 return { 5 presets: [ 6 [ 7 "@babel/preset-env", 8 { 9 useBuiltIns: "entry", 10 // caller.target will be the same as the target option from webpack 11 targets: api.caller(caller => caller && caller.target === "node") 12 ? { node: "current" } 13 : { chrome: "58", ie: "11" } 14 } 15 ] 16 ] 17 } 18}
Customized Loader
babel-loader
exposes a loader-builder utility that allows users to add custom handling
of Babel's configuration for each file that it processes.
.custom
accepts a callback that will be called with the loader's instance of
babel
so that tooling can ensure that it using exactly the same @babel/core
instance as the loader itself.
In cases where you want to customize without actually having a file to call .custom
, you
may also pass the customize
option with a string pointing at a file that exports
your custom
callback function.
Example
1// Export from "./my-custom-loader.js" or whatever you want. 2module.exports = require("babel-loader").custom(babel => { 3 // Extract the custom options in the custom plugin 4 function myPlugin(api, { opt1, opt2 }) { 5 return { 6 visitor: {}, 7 }; 8 } 9 10 return { 11 // Passed the loader options. 12 customOptions({ opt1, opt2, ...loader }) { 13 return { 14 // Pull out any custom options that the loader might have. 15 custom: { opt1, opt2 }, 16 17 // Pass the options back with the two custom options removed. 18 loader, 19 }; 20 }, 21 22 // Passed Babel's 'PartialConfig' object. 23 config(cfg, { customOptions }) { 24 if (cfg.hasFilesystemConfig()) { 25 // Use the normal config 26 return cfg.options; 27 } 28 29 return { 30 ...cfg.options, 31 plugins: [ 32 ...(cfg.options.plugins || []), 33 34 // Include a custom plugin in the options and passing it the customOptions object. 35 [myPlugin, customOptions], 36 ], 37 }; 38 }, 39 40 result(result) { 41 return { 42 ...result, 43 code: result.code + "\n// Generated by some custom loader", 44 }; 45 }, 46 }; 47});
1// And in your Webpack config 2module.exports = { 3 // .. 4 module: { 5 rules: [{ 6 // ... 7 loader: path.join(__dirname, 'my-custom-loader.js'), 8 // ... 9 }] 10 } 11};
customOptions(options: Object): { custom: Object, loader: Object }
Given the loader's options, split custom options out of babel-loader
's
options.
config(cfg: PartialConfig, options: { source, customOptions }): Object
Given Babel's PartialConfig
object, return the options
object that should
be passed to babel.transform
.
result(result: Result): Result
Given Babel's result object, allow loaders to make additional tweaks to it.
License
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
GitHub workflow tokens follow principle of least privilege
Details
- Info: topLevel 'contents' permission set to 'read': .github/workflows/ci.yml:6
- Info: no jobLevel write permissions found
Reason
security policy file detected
Details
- Info: security policy file detected: SECURITY.md:1
- Info: Found linked content: SECURITY.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: SECURITY.md:1
- Info: Found text in security policy: SECURITY.md:1
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
0 existing vulnerabilities detected
Reason
Found 21/25 approved changesets -- score normalized to 8
Reason
5 commit(s) and 2 issue activity found in the last 90 days -- score normalized to 5
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:22: update your workflow using https://app.stepsecurity.io/secureworkflow/babel/babel-loader/ci.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:24: update your workflow using https://app.stepsecurity.io/secureworkflow/babel/babel-loader/ci.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:45: update your workflow using https://app.stepsecurity.io/secureworkflow/babel/babel-loader/ci.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci.yml:47: update your workflow using https://app.stepsecurity.io/secureworkflow/babel/babel-loader/ci.yml/main?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/ci.yml:56: update your workflow using https://app.stepsecurity.io/secureworkflow/babel/babel-loader/ci.yml/main?enable=pin
- Info: 0 out of 4 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 third-party GitHubAction dependencies pinned
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 28 are checked with a SAST tool
Score
6.9
/10
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to babel-loader
craco-babel-loader
Rewire `babel-loader` loader in your `create-react-app` project using `craco`.
@remotion/babel-loader
Babel loader for Remotion
loader-fs-cache
A published package of https://github.com/babel/babel-loader/blob/master/src/fs-cache.js
craco-babel-loader-plugin
CRACO plugin for babel-loader