所以我对 webpack 还很陌生,在过去的一周里,我一直在努力将它实施到我的项目中,我使用了这个指南:https ://medium.com/@binyamin/creating-a-node-express-webpack -app-with-dev-and-prod-builds-a4962ce51334 我设法让大部分东西工作,但不能让 HMR 开始工作。感谢您的帮助,在此先感谢您。
这是我的 webpack.dev.config.js 文件:
const path = require('path')
const webpack = require('webpack')
const HtmlWebPackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
module.exports = {
entry: {
main: ['webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000?reload=true', './src/index.js']
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/',
filename: '[name].js'
},
devServer: {
contentBase: "dist",
overlay: true,
hot: true,
stats: {
colors: true
}
},
mode: 'development',
target: 'web',
devtool: '#source-map',
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
},
{
// Loads the javacript into html template provided.
// Entry point is set below in HtmlWebPackPlugin in Plugins
test: /\.pug$/,
use: ["html-loader", "pug-html-loader"]
//options: { minimize: true }
},
{
test: /\.scss$/,
use: ['style-loader', MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/html/pugtest.pug", //paima faila
filename: "index.html",
excludeChunks: ['server'],
inject: false
}),
new MiniCssExtractPlugin({
template: "./src/css/style.scss",
filename: "[name].css",
chunkFilename: "[id].css"
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
]
}
我的 server-dev.js 文件:
import path from 'path'
import express from 'express'
import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import config from '../../webpack.dev.config.js'
const app = express(),
DIST_DIR = __dirname,
HTML_FILE = path.join(DIST_DIR, 'index.html'),
compiler = webpack(config)
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
}))
app.use(webpackHotMiddleware(compiler))
app.get('*', (req, res, next) => {
compiler.outputFileSystem.readFile(HTML_FILE, (err, result) => {
if (err) {
return next(err)
}
res.set('content-type', 'text/html')
res.send(result)
res.end()
})
})
const PORT = process.env.PORT || 8080
app.listen(PORT, () => {
console.log(`App listening to ${PORT}....`)
console.log('Press Ctrl+C to quit.')
})
index.js 文件:
import logMessage from './js/logger'
import './css/style.scss'
// Log message to console
logMessage('A very warm welcome to Expack!!')
// Needed for Hot Module Replacement
if (typeof (module.hot) !== 'undefined') {
module.hot.accept() // eslint-disable-line no-undef
}
webpack.server.config.js 文件:
const path = require('path')
const webpack = require('webpack')
const nodeExternals = require('webpack-node-externals')
module.exports = (env, argv) => {
const SERVER_PATH = (argv.mode === 'production') ?
'./src/server/server-prod.js' :
'./src/server/server-dev.js'
return ({
entry: {
server: SERVER_PATH
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/',
filename: '[name].js'
},
target: 'node',
node: {
// Need this when working with express, otherwise the build fails
__dirname: false, // if you don't put this is, __dirname
__filename: false, // and __filename return blank or /
},
externals: [nodeExternals()], // Need this to avoid error when working with Express
module: {
rules: [{
// Transpiles ES6-8 into ES5
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}]
}
})
}
和我的文件结构:
express-webpack
/dist
/node_modules
/scr
/css
style.scss
/html
pugtest.pug
/js
logger.js
/server
server-dev.js
server-prod.js
index.js
.babelrc
package-lock.json
package.json
webpack.dev.config.js
webpack.prod.config.js
webpack.server.config.js
和我的 package.json 脚本:
"scripts": {
"dev": "webpack --mode development --config webpack.server.config.js && webpack --mode development --config webpack.dev.config.js",
"buildProd": "webpack --mode production --config webpack.server.config.js && webpack --mode production --config webpack.prod.config.js",
"start": "nodemon --watch config --watch ./dist/main.css ./dist/server.js"
},