我是webpack的新手,想要一个简单的配置,可以将我的SCSS,HTML和JS更改重新加载到浏览器中。我已经阅读了有关在style-loader
配置中使用options: { hmr: true }
选项的信息,以及使用webpack-dev-server
来执行此操作。我的更改导致重新编译成功,但我必须重新加载浏览器才能看到更改。这正是我理解的HMR的目的。
这是我的 webpack 配置:
// webpack v4
const path = require('path');
// update from 23.12.2018
const nodeExternals = require('webpack-node-externals');
// const ExtractTextPlugin = require('extract-text-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: { main: './src/index.js' },
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[hash].js'
},
target: 'node', // update from 23.12.2018
externals: [nodeExternals()], // update from 23.12.2018
module: {
rules: [
{
test: /.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /.scss$/,
use: [
// { loader: 'style-loader', options: { hmr: true } },
'style-loader',
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
]
}
]
},
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: 'style.[hash].css'
}),
new HtmlWebpackPlugin({
inject: false,
hash: true,
template: './src/index.html',
filename: 'index.html'
})
]
};
我尝试的最新方法是运行(根据本指南 https://medium.freecodecamp.org/how-to-combine-webpack-4-and-babel-7-to-create-a-fantastic-react-app-845797e036ff(:
node_modules/.bin/webpack-dev-server --mode development --open --hot --history-api-fallback
由于我在网络上找不到任何类似的问题,我认为这与我的配置有关。
这是我的package.json
:
{
"name": "webpack-4-tutorial",
"version": "1.0.0",
"description": "test",
"main": "index.js",
"license": "MIT",
"private": false,
"devDependencies": {
"@babel/core": "^7.4.3",
"@babel/preset-env": "^7.4.3",
"autoprefixer": "^9.5.1",
"babel-loader": "^8.0.5",
"clean-webpack-plugin": "^2.0.1",
"css-loader": "^2.1.1",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.6.0",
"node-sass": "^4.11.0",
"postcss-loader": "^3.0.0",
"precss": "^4.0.0",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"stylelint": "^10.0.1",
"stylelint-config-recommended": "^2.2.0",
"webpack": "^4.30.0",
"webpack-cli": "^3.3.1",
"webpack-dev-server": "^3.3.1",
"webpack-node-externals": "^1.7.2"
},
"scripts": {
"dev": "webpack --mode development --watch",
"build": "webpack --mode production"
}
}
最初根据本指南创建了配置文件,但它没有超出 webpack --watch
标志。
提前谢谢。
您是否尝试过直接添加到 web pack.config 文件中的 devServer 配置对象中?
devServer: {
hot: true,
}