由于很多浏览器不兼容es6,在使用es6开发过程中需要使用转换器对es6进行转换成es5,从而能够更好的在浏览器运行。在这里,我将会介绍如何使用webpack进行es6的开发,使用的是webpack的babel-loader转换器。

第一步 创建目录文件

创建目录如下:

/helloworld
index.js
hello.js
index.html
webpack.config.js

helloworld文件中,index.js是入口文件,hello.js是用es6编辑的js文件,index.html是首页,webpack.config.js是配置文件。

第二步 安装webpack

通过npm全局安装webpack

npm install webpack -g

第三步 编写配置文件

打开webpack.config.js,编辑如下:

var path = require('path');
module.exports = {
entry : './helloworld/index.js', //入口文件
output : { //输出文件
path : __dirname,
filename : 'bundle.js' //webpack运行完之后将生成一个bundle.js文件,用于将执行文件中的代码导入index.html
},
module : {
loaders : [ //加载器
{
test : path.join(__dirname,'es6'),
loader : 'babel-loader', //使用babel-loader加载器
query : {
presets : ['es2015'] //使用es2015转码规则
}
}
]
}
}

第四步 安装loaders

安装babel-loader:

npm install babel-loader --save-dev

安装转码规则:

npm install babel-preset-es2015 --save-dev

第五步 编写代码

  • helloworld/hello.js:
class Hello{
constructor(name,age){
this.name = name;
this.age = age;
}

say(){
return `我是${this.name},我今年${this.age}岁了`;
}
}

export default Hello;
  • helloworld/index.js
import Person from './hello.js';

let p = new Person('Zoe',20);
document.write(p.say());
  • index.html
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="">
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>

第六步 运行

在命令行中,直接输入webpack就能运行:

webpack

在大型项目中,可以添加一个颜色进度跳便于查看参数:

webpack --progress --colors

也可以使用watch来监视文件的变化:

webpack --watch

所以最后可以使用如下命令运行:

webpack --progress --colors --watch