开始入手webpack ,直接看的官方文档和demo,对于自动刷新这部分还是希望通过express 加载插件来控制,但是文档没有提供,经过参考github上其他高玩的套路,最终整理了一个基础的配置版本。
问题
webpack.NoErrorsPlugin is not a constructor
TypeError: webpack.optimize.OccurenceOrderPlugin is not a constructor
//解决方法:去掉。这两个方法在1.x 和 2.x才能使用。
目录结构
webpack.config.js 基础配置
//webpack config file
const path = require('path')
const webpack = require('webpack')
//自动生成html,或依赖模版
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
module.exports= {
mode : 'development',
//⭐⭐⭐ entry 此处需要注意,在app print 里面增加dev-client,具体内容在下面。
entry : {
app : ['./build/dev-client','./src/index.js'],
print : ['./build/dev-client','./src/print.js']
},
output : {
path : path.resolve(__dirname,'dist'),
filename : '[name].bundle.js',
publicPath : '/'
},
devtool : 'inline-source-map',
devServer : {
contentBase : './dist',
port : '9999'
},
plugins : [
//HMR
// new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
// new webpack.NoErrorsPlugin(),
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title : '管理输出啊'
})
],
module : {
rules : [
{
test : /\.css$/,
use : [
'style-loader',
'css-loader'
]
},{
test : /\.(png|jpg|gif|svg)$/,
use : ['file-loader']
},{
test : /\.(woff|woff2|eot|ttf|otf)$/,
use : ['file-loader']
}
]
}
}
express 服务端编码
const express = require('express');
const webpack = require('webpack')
const webpackMiddleWare =require('webpack-dev-middleware')
const app = express();
const config = require('./webpack.config')
const compiler = webpack(config)
app.use(webpackMiddleWare(compiler,{
publicPath : config.output.publicPath
}))
app.use(require('webpack-hot-middleware')(compiler))
let port = 9999;
app.listen(port,()=>{
console.log(`server is running at port ${port}`);
})
dev-client.js 编码
require('eventsource-polyfill')
var hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true')
hotClient.subscribe(function(event) {
if (event.action === 'reload') {
window.location.reload()
}
})
src/index.js src/print.js
这两个文件与官网一致,随便写几个即可。
package.json
{
"name": "webpack1",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"build": "webpack --config webpack.config.js",
"watch": "webpack --watch",
"start": "webpack-dev-server --open",
"server": " node ./build/dev"
},
"author": "chrunlee",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^2.0.1",
"css-loader": "^2.1.1",
"eventsource-polyfill": "^0.9.6",
"file-loader": "^3.0.1",
"html-webpack-plugin": "^3.2.0",
"style-loader": "^0.23.1",
"webpack-dev-server": "^3.3.1",
"webpack-hot-middleware": "^2.24.3"
},
"dependencies": {
"jquery": "^3.4.0",
"lodash": "^4.17.11",
"webpack": "^4.30.0"
}
}
以上
这里面主要要注意的就是 webpack.config 内的 entry即可。
代码下载 : http://res.chrunlee.cn/static/2019/4/15556443284321548.zip