使用es6+新語法編寫代碼,但是不能運行於低版本瀏覽器,須要將語法轉換成es5的。那就藉助babel7轉換,再加上webpack打包,實現代碼的轉換。html
轉換包括兩部分:語法和APInode
let、const這些是新語法。webpack
new promise()等這些是新API。git
類庫 utils.jses6
const name = 'weiqinl' let year = new Date().getFullYear() export { name, year }
index.jsgithub
import _ from 'lodash' import { name, year } from './utils' Promise.resolve(year).then(value => { console.log(`${name} - ${value} - ${_.add(1, 2)}`) })
安裝babel編譯器和對應的運行時環境web
npm install -D @babel/core @babel/preset-env @babel/plugin-transform-runtime @babel/polyfill babel-loader
並新建.babelrc
文件,裏面能夠配置不少東西,內容爲:npm
{ "presets": [ ["@babel/preset-env", { "useBuiltIns": "usage", "modules": false }] ], "plugins": [ [ "@babel/plugin-transform-runtime", { "corejs": false, "helpers": false, "regenerator": false, "useESModules": false } ] ], "comments": false }
webpack4,能夠零配置構建項目,那是由於它的不少配置值都默認了。在這裏,咱們須要本身配置。
首先安裝webpackpromise
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
[完]