首页 技术 正文
技术 2022年11月15日
0 收藏 992 点赞 2,697 浏览 1691 个字

demo 代码点此,如果对 babel 不熟,可以看一下babel 7 简单指北

webpack 使用 babel 来打包使用 es6 及以上语法的 js 文件是非常方便的,可以通过配置,将 es6 转化为 es5.

start


准备个空文件,执行如下命令:

npm init -y
npm i -D webpack webpack-cli
npm i -D babel-loader @babel/core

然后创建一个 dist 文件夹,创建一个 html 文件:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>webpack4 babel 篇</title>
<body>
<div id="root"></div>
<script type="text/javascript" src="bundle.js"></script></body>
</html>

根目录下创建 webpack.config.js,配置 webpack:

const path = require('path');module.exports = {
mode: 'development',
entry: {
main: './index.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
},
],
},
devtool: 'source-map',
// 出口
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
}

为了转化 es6 代码,要安装 babel 插件:

npm i -D @babel/preset-env @babel/polyfill

然后在根目录下创建 babel 配置文件 .babelrc:

{
"presets": [
[
"@babel/preset-env",
{
"useBuiltIns": "usage",
"targets": {
"browsers": ["last 2 versions", "ie >= 10"]
}
}
]
]
}

然后在根目录下创建 index.js:

const add = (x, y) => {
return new Promise((resolve, reject) => {
resolve( x + y);
});
}add(1, 2).then(res => console.log(res));

打包


终端执行打包:

npx webpack

打开 dist 目录下的 bundle.js,可以看见代码已经转为 es5,搜索 promise,会发现加上了 promise 的 polyfill:

// bundle.js...
var add = function add(x, y) {
return new Promise(function (resolve, reject) {
resolve(x + y);
});
};add(1, 2).then(function (res) {
return console.log(res);
});
...

访问 index.html,console 也打印正常。

防止全局污染


如果是写第三方库或者框架,使用 polyfill 可能会造成全局污染,所以可以使用 @babel/plugin-transform-runtime 防止全局污染。

安装:

npm i -D @babel/plugin-transform-runtime
npm i -S @babel/runtime @babel/runtime-corejs2

修改 babel 配置:

{
"plugins": [
[
"@babel/plugin-transform-runtime",
{
"corejs": 2,
"helpers": true,
"regenerator": true,
"useESModules": false
}
]
]
}

打包即可。

备注


这个主要是 babel 的配置。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,497
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,910
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,744
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,498
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,136
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,300