我试图在我的 webpack 配置中使用 HRM(热模块替换),首先我在 package.jsong 中设置了 --hot 选项:
"scripts": {
"start": "webpack-dev-server --hot"
}
另请注意,我正在使用 HtmlWebpackPlugin 为我创建一个 index.html 文件并将其放在“build”目录中,这是我的完整 webpack.config.js 文件:
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserJSPlugin = require('terser-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const WebpackManifestPlugin = require('webpack-manifest-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
// const webpack = require('webpack');
const mode = "development";
module.exports = {
mode: mode,
// watch: true,
devtool: "cheap-module-eval-source-map",
devServer: {
port: 9000,
// contentBase: path.resolve(__dirname, 'build')
},
entry: {
application: "./src/javascripts/index.js",
admin: "./src/javascripts/admin.js"
},
output: {
filename: mode === 'production' ? "[name]-[contenthash].js" : '[name].[hash].js',
path: path.resolve(__dirname, 'build'),
// publicPath: '/'
},
optimization: {
minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
},
plugins: [
new MiniCssExtractPlugin({
filename: mode === 'production' ? "[name]-[contenthash].css" : "[name]-[hash].css",
hmr: mode === 'production' ? false : true
}),
new CleanWebpackPlugin(),
new WebpackManifestPlugin(),
new HtmlWebpackPlugin({
template: './src/template.html',
// filename: '../index.html'
})
// new webpack.HotModuleReplacementPlugin()
],
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
},
{
test: /\.css$/i,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 1 } },
{
loader: 'postcss-loader',
options: {
plugins: [
require('autoprefixer')({
overrideBrowserslist: ['last 3 versions', 'ie > 9']
})
]
}
},
],
},
{
test: /\.scss$/i,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: 1 } },
{
loader: 'postcss-loader',
options: {
plugins: [
require('autoprefixer')({
overrideBrowserslist: ['last 3 versions', 'ie > 9']
})
]
}
},
'sass-loader'
],
},
{
test: /\.(png|jpg|gif|svg)$/i,
use: [
{
loader: 'file-loader',
options: {
limit: 8192,
name: '[name].[hash:7].[ext]'
},
},
{
loader: 'image-webpack-loader'
}
],
}
]
}
}
如您所见,我主要使用的条目./src/javascripts/index.js
是导入名为 application.scss 的文件的位置:
import application from "../stylesheets/application.scss"
application.scss 包含:
span{
background-color: blue;
}
因此,每当我更改位于我的 html 页面中的 span 的背景颜色时,我都想热重新加载页面。
当我运行时,npm run start
我更改了跨度的背景颜色,更新第一次工作(但它确实是一个完整的页面重新加载)然后如果我再次尝试更改背景颜色,则没有任何更新,我在控制台中看到的只是:
[HMR] Nothing hot updated. log.js:24
[HMR] App is up to date.
不确定这里缺少什么,但有人可以看到做错了什么?