This README is for babel-loader v8 + Babel v7If you are using legacy Babel v6, see the 7.x branch docs
This package allows transpiling JavaScript files using Babel and webpack.
Note: Issues with the output should be reported on the Babel Issues tracker.
webpack
4.x || 5.x
| babel-loader 8.x | babel 7.x
npm install -D babel-loader @babel/core @babel/preset-env webpack
webpack documentation: Loaders
Within your webpack configuration object, you'll need to add the babel-loader to the list of modules, like so:
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
['@babel/preset-env', { targets: "defaults" }]
]
}
}
}
]
}
See the babel
options.
You can pass options to the loader by using the options
property:
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
['@babel/preset-env', { targets: "defaults" }]
],
plugins: ['@babel/plugin-proposal-class-properties']
}
}
}
]
}
This loader also supports the following loader-specific option:
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.
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.
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.
customize
: Default null
. The path of a module that exports a custom
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 using babel-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 to context.myMetadataPlugin
within your webpack plugin's hooks & that function will be called with metadata
.
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.
Although we typically recommend not compiling node_modules
, you may need to when using libraries that do not support IE 11.
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.
{
test: /\.m?js$/,
exclude: {
and: [/node_modules/], // Exclude libraries in node_modules ...
not: [
// Except for a few of them that needs to be transpiled because they use modern syntax
/unfetch/,
/d3-array|d3-scale/,
/@hapi[\\/]joi-date/,
]
},
use: {
loader: 'babel-loader',
options: {
presets: [
['@babel/preset-env', { targets: "ie 11" }]
]
}
}
}
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
.
rules: [
// the 'transform-runtime' plugin tells Babel to
// require the runtime instead of inlining it.
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
['@babel/preset-env', { targets: "defaults" }]
],
plugins: ['@babel/plugin-transform-runtime']
}
}
}
]
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:
// ...
new webpack.ProvidePlugin({
'Promise': 'bluebird'
}),
// ...
The following approach will not work either:
require('@babel/runtime/core-js/promise').default = require('bluebird');
var promise = new Promise;
which outputs to (using runtime
):
'use strict';
var _Promise = require('@babel/runtime/core-js/promise')['default'];
require('@babel/runtime/core-js/promise')['default'] = require('bluebird');
var 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:
// bootstrap.js
require('@babel/runtime/core-js/promise').default = require('bluebird');
// ...
require('./app');
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):
{
test: /\.m?js$/,
loader: 'babel',
}
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:
{
test: /\.m?js$/,
loader: 'babel-loader',
}
core-js
and webpack/buildin
will cause errors if they are transpiled by Babel.
You will need to exclude them form babel-loader
.
{
"loader": "babel-loader",
"options": {
"exclude": [
// \\ for Windows, / for macOS and Linux
/node_modules[\\/]core-js/,
/node_modules[\\/]webpack[\\/]buildin/,
],
"presets": [
"@babel/preset-env"
]
}
}
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
:
// webpack.config.js
module.exports = {
// ...
output: {
// ...
environment: {
// ...
arrowFunction: false, // <-- this line does the trick
},
},
};
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:
// babel.config.js
module.exports = api => {
return {
plugins: [
"@babel/plugin-proposal-nullish-coalescing-operator",
"@babel/plugin-proposal-optional-chaining"
],
presets: [
[
"@babel/preset-env",
{
useBuiltIns: "entry",
// caller.target will be the same as the target option from webpack
targets: api.caller(caller => caller && caller.target === "node")
? { node: "current" }
: { chrome: "58", ie: "11" }
}
]
]
}
}
babel-loader
exposes a loader-builder utility that allows users to add custom handlingof Babel's configuration for each file that it processes.
.custom
accepts a callback that will be called with the loader's instance ofbabel
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
, youmay also pass the customize
option with a string pointing at a file that exportsyour custom
callback function.
// Export from "./my-custom-loader.js" or whatever you want.
module.exports = require("babel-loader").custom(babel => {
function myPlugin() {
return {
visitor: {},
};
}
return {
// Passed the loader options.
customOptions({ opt1, opt2, ...loader }) {
return {
// Pull out any custom options that the loader might have.
custom: { opt1, opt2 },
// Pass the options back with the two custom options removed.
loader,
};
},
// Passed Babel's 'PartialConfig' object.
config(cfg) {
if (cfg.hasFilesystemConfig()) {
// Use the normal config
return cfg.options;
}
return {
...cfg.options,
plugins: [
...(cfg.options.plugins || []),
// Include a custom plugin in the options.
myPlugin,
],
};
},
result(result) {
return {
...result,
code: result.code + "\n// Generated by some custom loader",
};
},
};
});
// And in your Webpack config
module.exports = {
// ..
module: {
rules: [{
// ...
loader: path.join(__dirname, 'my-custom-loader.js'),
// ...
}]
}
};
customOptions(options: Object): { custom: Object, loader: Object }
Given the loader's options, split custom options out of babel-loader
'soptions.
config(cfg: PartialConfig): Object
Given Babel's PartialConfig
object, return the options
object that shouldbe passed to babel.transform
.
result(result: Result): Result
Given Babel's result object, allow loaders to make additional tweaks to it.
babel 概述 Babel 是一个 JavaScript 编译器,它是一个工具链,主要的用途就是在旧的浏览器或环境中将ECMAScript 2015+ 代码转换为向后兼容的 js 代码。 案例分析 //demo a.js [1,2,3].map(item => item+20) 官方给的是@babel/cli,其内部包含调用了@babel/node @babel/core 提供的是基础 ap
Webpack 自带加载 js模块 的功能,但是他只能做 js模块化 的打包,并不能转换 js 里面的代码,比如将 ES6 转换成 ES5。 有时候我们的代码还能运行,这纯靠浏览器的解析。如果浏览器版本比较低的话,运行的时候就会发生错误。 因此,我们写代码的时候是需要转化的,这个转换的工具,就是babel。babel 和 webpack 的结合,就需要一个 babel-loader。 一、babe
由于webpack只能打包处理以 .js 后缀名结尾的模块,需要额外的loader加载器才可以处理其他类型的文件,如.css、 .less等相关文件 安装css-loader //默认安装最新版本 npm i style-loader css-loader -D //指定安装版本 npm i style-loader@3.0.0 css-loader@5.2.6 -D 在webpack.con
PS D:\vuelearn\VueLearn\03-前端模块化\LearnVuejs04-v2\01-webpack的使用\03-webpack的loader> npm run build > metpkg@1.0.0 build D:\vuelearn\VueLearn\03-前端模块化\LearnVuejs04-v2\01-webpack的使用\03-webpack的loader > web
1,core-js:将我们的代码编译后成为浏览器可执行的代码,其中主要处理 ES 的API,他是运行的一个API 补丁包集合, 也可以理解为:它是JavaScript标准库的 polyfill。 官方库对他介绍的形容: 1.1它支持最新的 ECMAScript 标准 1.2它支持ECMAScript 标准库提案 1.3它支持一些 WHATWG / W3C 标准(跨平台或者 ECMAScript
前言 webpack 前端工程化打包的一项重要技术 今天给大家来学习一下关于babel-loader的应用,也是在者方面进行了踩坑 流程 流程分为三步 安装 babel-loader 、 @babel/core、@babel/plugin-proposal-decorators 配置 规则 新建babel.config.js 配置插件 操作流程 安装 npm i babel-loader@8.2.
根据官网https://www.npmjs.com/package/babel-loader要对应版本 一、babel7.X版本 1.要安装的包 第1套包:npm i babel-core babel-loader@7 babel-plugin-transform-runtime –D(千万记得是babel-loader@7,不是其他的) 第2套包:npm I babel-preset-env
前因 webpack 自身可以自动加载JS文件,就像加载JSON文件一样,无需任何 loader。可是,加载的JS文件会原样输出,即使JS文件里包含ES6+的代码,也不会做任何的转化。那么我们就需要Babel帮忙了,Babel 是一个 JavaScript 编译器,可以将 ES6+ 转化成 ES5。在Webpack里使用Babel,需要使用 babel-loader 依赖安装 npm instal
问题内容: 我是React + Webpack的初学者。 我在Hello World Web应用程序中发现一个奇怪的错误。 我在webpack中使用babel-loader来帮助我将jsx转换为js,但是babel似乎无法理解jsx语法。 这是我的依赖项: 这是我的 这是我的 这是错误消息 谢谢你们 问题答案: 添加“ babel-preset-react” 并在webpack.config.js
问题内容: 我是React + Webpack的初学者。 我在Hello World Web应用程序中发现了一个奇怪的错误。 我在webpack中使用babel-loader来帮助我将jsx转换为js,但是babel似乎无法理解jsx语法。 这是我的依赖项: 这是我的 这是我的 这是错误消息 谢谢你们 问题答案: 添加“ babel-preset-react” 并在webpack.config.j
本文向大家介绍webpack使用 babel-loader 转换 ES6代码示例,包括了webpack使用 babel-loader 转换 ES6代码示例的使用技巧和注意事项,需要的朋友参考一下 本文介绍了webpack使用 babel-loader 转换 ES6代码示例,分享给大家,具体如下: 查询各个 loader的使用,可以在官网上查询。https://www.npmjs.com (一)安装
我正在静态站点上使用本机es6模块。 在部署之前,我通过Babel传递js文件 //网页包。配置。js //. babelrc 默认情况下,babel会将模块转换为公共js,尽管我的代码中有一个标志“modules”:false。巴别塔 我不想让babel把模块变成通用的,我只想把除了导入和导出之外的所有东西都变成es2015,这样我就可以在浏览器中使用原生模块了 像这样://main.js之前
热模块更换工作没有加载器,另一个加载器,或另一个预设。 但它不能与巴贝尔-装载机和预置的ES2015。es2016工作。预置“env”也有同样的问题。 是否有可能用es2015或ENV替换webpack热模块? 以下是我的文件: webpack.config.js print.js index.html package.json index.js .巴贝尔c
问题内容: 尝试使用Webpack4和Babel7构建React应用时,我遇到以下错误。 ./src/index.js中的错误模块构建失败(来自./node_modules/babel-loader/lib/index.js):错误:无法从’/ Users / me / Desktop /找到模块’babel-preset-react’ reflask’-如果要解析“ react”,请使用“ mo