我的 Webpack 配置有問題。寫入標簽后,影像出現,但devServer在頁面重新加載后立即洗掉樣式應用程式后的所有圖片。并且在標簽中再次添加路徑之前它不會回傳。請參閱此螢屏截圖視頻以更好地了解正在發生的事情。
webpack.config.js:
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
let mode = 'development'
let target = 'web'
if (process.env.NODE_ENV === 'production') {
mode = 'production'
target = 'browserslist'
}
const plugins = [
new HtmlWebpackPlugin({
template: './index.html',
}),
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css',
}),
]
module.exports = {
mode,
plugins,
target,
context: path.resolve(__dirname, 'src'),
entry: {
main: './main.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
assetModuleFilename: 'assets/[hash][ext][query]',
clean: true,
},
optimization: {
splitChunks: {
chunks: 'all',
},
},
devServer: {
static: {
directory: path.join(__dirname, 'src'),
},
compress: true,
open: true,
hot: true,
port: 3001,
},
resolve: {
extensions: ['.js', '.ts', '.jsx', '.tsx'],
},
module: {
rules: [
{
test: /\.(html)$/,
use: ['html-loader'],
},
{
test: /\.(s[ac]|c)ss$/i,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
},
{
test: /\.(png|jpe?g|gif|svg|webp|ico)$/i,
type: mode === 'production' ? 'asset' : 'asset/resource',
},
{
test: /\.(woff2?|eot|ttf|otf)$/i,
type: 'asset/resource',
},
{
test: /\.(js|jsx)?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
},
},
},
{
test: /\.(ts|tsx)?$/,
exclude: /node_modules/,
use: {
loader: 'ts-loader',
},
},
],
},
}
uj5u.com熱心網友回復:
新答案:
將我的webpack-dev-server版本從升級v3.11.2到v4.9.1.
根據您以前的版本,可能會對
devServer進入webpack.config.js. 如果您有錯誤,請參閱檔案。
為此,靜態目錄devServer應該與 Webpack 的輸出目錄相同。對于這個問題,它應該dist代替src.
如果您還沒有,您可能需要使用HtmlWebpackPlugin
index.html在輸出檔案夾中提供服務。
devServer: {
static: {
directory: path.join(__dirname, "dist"),
},
// ....
},
老答案:
我有同樣的問題。我意識到在 JavaScript 檔案中匯入的影像可以import正常作業。問題來自 HTML 檔案中的影像,使用html-loader處理。我搜索了很多,沒有找到為什么會這樣,但這里有一種方法可以避免這個問題:
每次添加新影像時,請停止開發服務器、運行
npm run build或任何用于構建專案的命令。然后運行npm start。之后,它作業正常。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/485976.html
標籤:javascript 节点.js 网页包
