https://www.cnblogs.com/guolao/archive/2019/07/25/11244758.html
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 的配置。
以下是狗尾
import {firstName,lastName} from './export.js'
//import {pako } from './pako/index.js'
const pako = require('./pako/index.js')
console.log(firstName + " " + lastName);
// K 线相关
let hburl = 'wss://api.huobipro.com/ws'; // 实时币种价格
let haurl = 'wss://api.hadax.com/ws';
let requestK = { // 请求对应信息的数据
req: "market.bchusdt.kline.1min",
id: "bchusdt",
from: Math.round(new Date().getTime()/1000) - 60,
to: Math.round(new Date().getTime()/1000)
};
let subK = { // 订阅数据
sub: "market.bchusdt.kline.1min",
id: "bchusdt"
};
let socketK = new WebSocket(haurl);
socketK.onopen = function () {
console.log("connection establish");
socketK.send(JSON.stringify(subK));
socketK.send(JSON.stringify(requestK));
};
socketK.onmessage = function (event) {
let blob = event.data;
let reader = new FileReader();
reader.onload = function (e) {
let ploydata = new Uint8Array(e.target.result);
let msg = pako.inflate(ploydata, {to: 'string'});
handleData(msg);
};
reader.readAsArrayBuffer(blob, "utf-8");
};
socketK.onclose = function () {
console.log('connection closed');
};
// 处理接收到的信息
function handleData(msg) {
let data = JSON.parse(msg);
if (data.ping) {
// 如果是 ping 消息
sendHeartMessage(data.ping);
} else if (data.status === 'ok') {
// 响应数据
handleReponseData(data);
} else {
// 数据体
console.log(data)
}
}
// 发送响应信息
function sendHeartMessage(ping) {
socketK.send(JSON.stringify({"pong": ping}));
}
function handleReponseData(data) {
}