过程

  1. webpack.config.js 改成 webpack.config.babel.js
  2. 在根目录添加 .babelrc
  3. 安装 babel-core babel-loader babel-preset-es2015

webpack.config.babel.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import path from 'path'

export default {
entry: [
path.resolve(__dirname, './src/index.js')
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/'
},
module: {
rules: [
{
test: /\.js$/,
use: [
{
loader: 'babel-loader'
}
],
exclude: [
resolve(__dirname, './node_modules/')
]
}
]
}
}

注意: 这里须要将 exclude: [resolve(__dirname, './node_modules/')] 加入,否则打包后的代码会包括 node_modules 下的文件,而且不能写成 '/node_modules/'

package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
"name": "webpacklearning",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack --config webpack.config.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-runtime": "^6.26.0"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.6.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-3": "^6.24.1",
"webpack": "^3.5.6"
}
}

.babelrc

这里注意一点是 不能使用 modules: false modules: false配置项是告诉es2015 preset避免把import statements编译成CommonJS,这样Webpack才好做tree shaking

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
"presets": [
[
"env",
{
"targets": {
"browsers": [
"last 2 versions",
"ie >= 9"
],
"node": "current"
}
}
],
"react",
"stage-3"
],
"plugins": [
"react-hot-loader/babel",
"transform-runtime"
]
}