github
以往文章:
重温webpack:骨架搭建
准备
dev-server需要解决我们的哪些问题?
- 开发环境热模块替换
- 自动刷新
- debug追踪到原文件。source-map的解释
开启dev-server要区分好生产环境与开发环境,先前,我们都是直接生成生产环境,现在我们需要使用webpack-merge进行区分。
npm i dev-server -D
- 修改
package.json
"script": {
"build": "./build/build.js",
"dev": "dev-server --config ./build/dev.js"
}
- 调整基础结构,拆分生产环境与开发环境。生产环境构建
// 在之前的基础上,我们在开发环境中并不需要单独打包css
/**** base config ****/
const utils = require('./utils')
const path = require('path')
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')
module.exports={
entry:utils.entries(),
output:{
filename:'[name].js',
path:path.resolve(__dirname,'../dist')
},
module: {
rules: [
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
use: [
{
loader: 'file-loader',
options: {
name: 'img/[name].[hash:7].[ext]'
}
}
]
},
{
test: /\.html$/,
use: 'html-loader'
}
]
},
plugins:[
new CleanWebpackPlugin(),
].concat(utils.htmlPlugins())
}
/**** 生产环境 build.js ****/
const baseConfig = require('./webpack.config')
const webpack = require('webpack')
const merge = require('webpack-merge')
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')
const config = merge(baseConfig, {
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextWebpackPlugin.extract({
fallback:'style-loader',
use:'css-loader'
})
}
],
},
plugins: [
new ExtractTextWebpackPlugin('css/[name].css')
]
})
webpack(config, function(err){
if (err) throw err
console.log('product......')
})
- 配置dev-server
/**** dev.js ****/
const baseConfig = require('./webpack.config')
const merge = require('webpack-merge')
const webpack = require('webpack')
const config = merge(baseConfig, {
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
// https://segmentfault.com/a/1190000004280859
// devtool: 'inline-source-map',
devServer: {
contentBase: '/',
// 监听的端口
port: 8080,
// 使用热模块替换
hot: true,
// 自动打开页面
open: true,
// 显示打包进度
progress: true,
// 报错在页面打出
overlay: {
warnings: false,
errors: true
},
// watchOptions: {
// // 文件更改后延迟刷新,毫秒为单位进行轮询。
// poll: 5000
// //
// aggregateTimeout: 1000
// }
},
plugins: [
// 加载热模块替换包
new webpack.HotModuleReplacementPlugin()
]
})
module.exports = config
// package.json
- "dev": "dev-server --config ./build/dev.js"
+ "dev": "dev-server --config ./build/dev.js --inline" // 实时更新
// 很疑惑的是inline配置在devServer中并不启作用,放在command反而是可行的
公共模块的提取
代码分离是 webpack 中最引人注目的特性之一。此特性能够把代码分离到不同的 bundle 中,然后可以按需加载或并行加载这些文件。代码分离可以用于获取更小的 bundle,以及控制资源加载优先级,如果使用合理,会极大影响加载时间。
代码分离
/**** build.js ****/
// 相当于为每个入口文件提取公共模块
+ const utils = require('./utils')
+ new webpack.optimize.CommonsChunkPlugin({
+ name: 'common',
+ filename: 'common/[name].bundle.js',
+ minChunks: utils.htmlPlugins().length
+ }),
/**** utils.js ****/
let conf = {
filename:filename+'.html',
template:path.resolve(PAGE_PATH,filename+'/'+filename+'.html'),
- chunks:[filename]
+ chunks:[filename, 'common']
inject:true,
}
最后, 更多细节可以从我的github上clone下来试试~~
网友评论