webpack.config.js包含:
- 入口文件
- 输出目录
- js分离 chunk webpack.optimize.CommonsChunkPlugin
- css分离 extract-text-webpack-plugin
- html加载html-webpack-plugin
- es6loader babel-loader
- sassloader style-loader css-loader sass-loader (记得下载 node-sass)
- 图片loader file-loader
- 热更新devServer
webpack.config.js
var path = require('path');
var webpack = require('webpack');
var HtmlwebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var ROOT_PATH = path.resolve(__dirname);
var APP_PATH = path.resolve(ROOT_PATH, 'app');
var BUILD_PATH = path.resolve(ROOT_PATH, 'build');
module.exports= {
entry: {
app: path.resolve(APP_PATH, 'index.jsx'), //入口文件
common1: path.resolve(APP_PATH, 'common.js'), //公共入口文件----antd/element-ui/...带ui的 为了生成公共样式文件
//添加要打包在vendors里面的库
vendors: ['jquery'] //react/react-dom....
},
output: {
path: BUILD_PATH,
filename: 'js/[name].min.js'
},
//enable dev source map
devtool: 'eval-source-map',
//enable dev server
devServer: {
host: '127.0.0.1',
port: '8099',
historyApiFallback: true
},
//babel重要的loader在这里
module: {
loaders: [
{//jsx loader
test: /\.jsx?$/,
loader: 'babel-loader',
include: APP_PATH
},
{//scss loader
test: /\.scss$/,
loaders: ExtractTextPlugin.extract({fallback:'style-loader', use: 'css-loader!sass-loader'}),
include: APP_PATH
},
{//img loader
test: /\.(png|jpg)$/,
loader: 'file-loader?limit=40000&name=images/[name].[hash:8].[ext]'
}
]
},
plugins: [
new HtmlwebpackPlugin({
title: 'My first react app',
filename:'view/index.html', //生成的html存放路径,相对于 path
// template:'src/view/index.html', //html模板路径
inject:true, //允许插件修改哪些内容,true/'head'/'body'/false,
// chunks:['vendors','app'],//加载指定模块中的文件,否则页面会加载所有文件
hash:false, //为静态资源生成hash值
minify:{ //压缩HTML文件
removeComments:false, //移除HTML中的注释
collapseWhitespace:false //删除空白符与换行符
}
}),
//压缩代码
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
//把入口文件里面的数组打包成vendors.js
new webpack.optimize.CommonsChunkPlugin({
name: ["common", "common1", "vendors"], //common1.js 打包common.js vendors打包jquery
minChunks: 2 //引用2次及以上的打包到common里面
}),
new ExtractTextPlugin({filename: 'css/[name].[contenthash:8].css', allChunks: true}),
//在文件开头插入banner
new webpack.BannerPlugin("The file is creted by zhulu.--"+ new Date()),
],
//路径别名
resolve: {
alias: {
"_C": path.resolve(APP_PATH + "/components")
}
}
}
package.json
...
"scripts": {
"start": "webpack-dev-server --hot --inline",
"build": "webpack --progress --profile --colors"
},
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.4",
"extract-text-webpack-plugin": "^2.1.2",
"file-loader": "^0.11.2",
"html-webpack-plugin": "^2.30.1",
"jquery": "^3.2.1",
"node-sass": "^4.5.3",
"sass-loader": "^6.0.6",
"style-loader": "^0.18.2",
"webpack": "^2.7.0",
"webpack-dev-server": "^2.7.1"
},
"dependencies": {
"react": "^15.6.1",
"react-dom": "^15.6.1"
}
...