由于ES6语法在各个浏览器上支持的情况各不相同,所以在使用ES6语法时需要使用babel经过一次编译,将ES6语法编译为ES5语法,下面就开始搭建一个基于webpack+babel的ES6语法运行环境:
1.需要安装的包
- webpack(安装webpack,必装)
- babel-loader和babel-core(babel转码器,必装)
- babel-preset-es2015(转码规则,以es2015规则转码,必装)
- webpack-dev-server(浏览器热更新使用,选装)
可以使用下面一条命令快速安装:
cnpm install babel-loader babel-core babel-preset-es2015 webpack webpack-dev-server --save-dev
2.目录结构说明
D:\ES6-ENV
│ .babelrc
│ index.html
│ package.json
│ webpack.config.js
│
├─dist
├─node_modules
└─src
└─ main.js
1.ES6-ENV: 项目名
2..babelrc:babel的配置文件
3.index.html:访问的页面
4.webpack.config.js:webpack配置文件
5.dist:webpack打包后的输出文件
6.src/main.js:编写es6代码文件
3.babel配置文件.babel
{
"presets":[
"es2015"
],
"plugins":[]
}
4.webpack配置文件webpack.config.js
var path = require('path');
module.exports = {
//入口文件
entry:'./src/main.js',
//出口文件
output:{
filename:'bundle.js', //出口文件名
path: path.resolve(__dirname,'dist') //出口文件路径
},
module:{
rules:[
{
test:/\.js$/,
use:[
{
loader:'babel-loader'
}
],
exclude: [
//排除的不转换node_modules下面的.js文件
path.resolve(__dirname, 'node_modules')
]
}
]
}
}
5.package.json
{
"name": "es6-env",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "webpack-dev-server --port 8080 --inline --hot --open"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.11.0"
}
}
6.运行
npm run dev