webpack快速配置

Posted by yuk on 2016-03-28

使用webpack打开和调试React组件。安装配置如下

全局安装

1
npm install -g webpack

配置文件 webpack.config.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
var webpack = require('webpack');
var commonsPlugin = new webpack.optimize.CommonsChunkPlugin('common.js');

module.exports = {
entry: {
entry1: './entry/entry1.js',
entry2: './entry/entry2.js'
},
output: {
publicPath: "http://localhost:8080/assets/",
path: __dirname,
filename: '[name].entry.js'
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [{
test: /.js$/,
loader: 'babel-loader'
}, {
test: /.jsx$/,
loader: 'babel-loader!jsx-loader?harmony'
}]
},
plugins: [commonsPlugin]
};

执行打包

1
webpack --config webpack.config.js

配置调试环境 webpack.server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require("./webpack.config.js");

config.entry.index.unshift("webpack-dev-server/client?http://localhost:8080"); // 将执替换js内联进去
config.entry.index.unshift("webpack/hot/only-dev-server");

var compiler = webpack(config);
var server = new WebpackDevServer(compiler, {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
stats: {
colors: true // 用颜色标识
},
});
server.listen(8080);

启动调试服务器

1
node webpack.server.js

其他具体内容基本翻阅官网文档可以找到:

webpack官网教程 ,轻松入门React和Webpack

ES7特性

补充 遇到一些要使用es7特性的东西,修改loaders里面js(x)的部分

1
2
3
4
5
{
test : /.(js|jsx)$/,
exclude: /node_modules/,
loaders: ['react-hot','babel?presets[]=es2015&presets[]=react&presets[]=stage-0&plugins[]=transform-decorators-legacy']
}

16-4.12补充:

调试的时候如果设置.babelrc中的env参数
再正式环境时候得去除env里面的内容。为了更简便改成在webpack.server.js调试中加入预设和插件

1
2
3
4
5
6
7
8
9
10
config.module.loaders[0].query.presets.push("react-hmre");
config.module.loaders[0].query.plugins.push([
'react-transform', {
transforms: [{
transform : 'react-transform-hmr',
imports : ['react'],
locals : ['module']
}]
}
]);