使用es6+新语法编写代码,可是不能运行于低版本浏览器,需要将语法转换成es5的。那就借助babel转换,再加上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编译器和对应的运行时环境
并新建 .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.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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。
新闻热点
疑难解答