使用es6+新語法編寫代碼,可是不能運行於低版本瀏覽器,需要將語法轉換成es5的。那就借助babel7轉換,再加上webpack打包,實現代碼的轉換。
轉換包括兩部分:語法和API
let、const這些是新語法。
new promise()等這些是新API。
簡單代碼
類庫 utils.js
const name = 'weiqinl'
let year = new Date().getFullYear()
export { name, year }
index.js
import _ from 'lodash'
import { name, year } from './utils'
Promise.resolve(year).then(value => {
console.log(`${name} - ${value} - ${_.add(1, 2)}`)
})
babel轉換
安裝babel編譯器和對應的運行時環境
npm install -D @babel/core @babel/preset-env @babel/plugin-transform-runtime @babel/polyfill babel-loader
並新建.babelrc
文件,里面可以配置很多東西,內容為:
{
"presets": [
["@babel/preset-env", {
"useBuiltIns": "usage",
"modules": false
}]
],
"plugins": [
[
"@babel/plugin-transform-runtime", {
"corejs": false,
"helpers": false,
"regenerator": false,
"useESModules": false
}
]
],
"comments": false
}
webpack構建
webpack4,可以零配置構建項目,那是因為它的很多配置值都默認了。在這里,我們需要自己配置。
首先安裝webpack
npm i webpack webpack-cli -D
然后創建一個webpack.config.js
文件
const path = require('path');
module.exports = {
mode: "production",
entry: ['@babel/polyfill', './src/index.js'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].bundle.js'
},
module: {
rules: [{
test: /\.js$/,
include: [
path.resolve(__dirname, 'src')
],
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
}]
}
}
使用
webpack構建打包好的js文件,我們將其引入到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>webpack-babel-es6</title>
</head>
<body>
webpack構建由babel轉碼的es6語法,支持es6語法和API<br />
請查看瀏覽器控制台
<script src="./dist/main.bundle.js"></script>
</body>
</html>
運行該html,可以看到控制台有內容輸出weiqinl - 2018 - 3
最后的目錄結構:
可以git查看源碼https://github.com/weiqinl/demo/tree/master/webpack-bable-es6
[完]