当前浏览器对于es6语法支持程度还不是很高,我们可以通过webpack打包工具以及babel等转换es6语法,来实现浏览器支持es6语法。当然也有很多工具可以进行转换,比如使用SystemJS都可以,SystemJS有一个缺点就是网速要不好,特别慢,不过他也是很方便的,不用像在webpack中进行配置很多,只需要在script标签中引入,或者是npm安装就可以使用,不需要配置很多,这样可以使我们专注于代码的编写,我这里是使用webpack以及babel进行转换,通过安装了lodash来测试是否转换成功。
npm init
生成一个配置文件packe.json,内容如下
{
"name": "es6demo",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"lodash": "^4.17.11"
},
"devDependencies": {
"@babel/core": "^7.2.2",
"@babel/plugin-transform-runtime": "^7.2.0",
"@babel/polyfill": "^7.2.5",
"@babel/preset-env": "^7.2.3",
"babel-loader": "^8.0.4",
"webpack": "^4.28.3",
"webpack-cli": "^3.1.2"
}
}
npm install lodash
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
}
npm install webpack-cli --save-dev
也可以是这样,是上面的缩写
npm install 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'
},//webpack是通过模块加载了,下面是定义模块的加载方式
module: {
rules: [{
test: /\.js$/,//那种类型的文件,以js结尾的正则表达式
include: [
path.resolve(__dirname, 'src')
],
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
}]
}
}
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack --mode development"
},
整体代码如下:
{
"name": "es6demo",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack --mode development"
},
"author": "",
"license": "ISC",
"dependencies": {
"lodash": "^4.17.11"
},
"devDependencies": {
"@babel/core": "^7.2.2",
"@babel/plugin-transform-runtime": "^7.2.0",
"@babel/polyfill": "^7.2.5",
"@babel/preset-env": "^7.2.3",
"babel-loader": "^8.0.4",
"webpack": "^4.28.3",
"webpack-cli": "^3.1.2"
}
}
import { uniq } from 'lodash';
const arr = [1, 22, 1, 22, 123, 123, 2255, 22];
console.log(uniq(arr)); /* 用于给数组去重*/
npm run start
然后就看到我们的dist文件夹中会多出一个main.bundle.js文件,这个就是我们转换并打包的文件,然后在我们的html页面中引入这个文件,打开控制台,会出现我们的结果;如下: