想知道是否可以帮忙-
Webpack正在使我脱发。
我有一个dist文件夹,其中设置了js,img和css子文件夹。 我希望webpack编译我的: src / js / index.js转换为dist / js 和我的src / main.scss到dist / css中。然后我想要 webpack-dev-server可以观看dist文件,因此,如果我对src进行更改,它将在工作时立即显示。
这听起来很简单,但是我花了一天的大部分时间来实现它。
这是我的配置文件的样子:
var path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: ['babel-polyfill', './src/js/index.js'], //this is the correct entry point, and I have imported my main.scss into this file
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/main.js'
// it's already going to the dist folder, but is this path correct? I've tried /js/main.js - doesn't work
},
devServer: {
contentBase: './dist'
},
module: {
rules: [
{
test: /\.js$/,
use: ['babel-loader']
},
{
test: /\.scss$/,
use: [ MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: '/css/styles.css',
}),
new HtmlWebpackPlugin({
inject: false,
hash: true,
template: './src/index.html',
filename: 'index.html'
})
]
}
package.json:
{
"name": "webpack-sass",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "webpack --mode development",
"build": "webpack --mode production",
"start": "webpack-dev-server --mode development --open"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"css-loader": "^1.0.0",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.4.1",
"node-sass": "^4.9.2",
"sass-loader": "^7.0.3",
"style-loader": "^0.21.0",
"webpack": "^4.16.1",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.4"
},
"dependencies": {
"babel-polyfill": "^6.26.0"
}
}
答案 0 :(得分:0)
要使热重装工作正常
将此添加到您的webpack文件中
const webpack = require('webpack');
更新
devServer: {
contentBase: './dist'
},
到
devServer: {
contentBase: './dist'
hot: true, //this is important
},
然后
将new webpack.HotModuleReplacementPlugin()
添加到插件部分
plugins: [
new MiniCssExtractPlugin({
filename: '/css/styles.css',
}),
new HtmlWebpackPlugin({
inject: false,
hash: true,
template: './src/index.html',
filename: 'index.html'
}),
new webpack.HotModuleReplacementPlugin()
]
然后在您的index.js
if (module.hot) {
module.hot.accept('./yourImportedComponent.js', function() {
})
}
在webpack网站Webpack HMR
上详细解释了上述步骤