现在无论是打包后,还是直接执行npm run start
都无法加载背景图,而且打包后生成了三张图片,这种要怎么改呢?
执行npm run start
后,图片的请求位置
http://xx.xx.xxx.xxx:5555/b20e61d18b6df4c91184.png
打包后文件
打包后背景图片加载位置
package.json 文件启动相关
"scripts": {
"start": "npx webpack serve --open --mode development",
"build": "npx webpack --config webpack.config.js --mode production"
}
webpack.config.js
配置
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/main.js',
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
}),
new webpack.DefinePlugin({
// 定义特性标志
__VUE_OPTIONS_API__: JSON.stringify(true),
__VUE_PROD_DEVTOOLS__: JSON.stringify(false), // 或 true,根据需求配置
__VUE_PROD_HYDRATION_MISMATCH_DETAILS__: JSON.stringify(false) // 或 true,根据需求配置
})
// new webpack.DefinePlugin({
// __VUE_OPTIONS_API__: 'true',
// __VUE_PROD_DEVTOOLS__: 'false',
// __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: 'false'
// })
],
module: {
rules: [
{
test: /\.m?js$/, // 匹配 .js 或 .mjs 文件
exclude: /node_modules/, // 排除 node_modules 目录(可选,根据实际情况调整)
use: {
loader: 'babel-loader',
},
},
{
test: /\.s[ac]ss$/i,
use: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
// type: 'asset/resource',
// generator: {
// filename: 'img/[hash][ext][query]' // 局部指定输出位置
// },
use: [
{
loader: 'file-loader',
options: {
outputPath: 'img',
publicPath: 'dist/img',
name: '[name].[contenthash].[ext]',
},
},
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
progressive: true,
quality: 65,
},
pngquant: {
quality: [0.65, 0.9],
speed: 4,
},
gifsicle: {
interlaced: false,
},
// 测试环境是否跳过压缩图片
bypassOnDebug: false,
}
}
]
}
// {
// test: /\.(png|svg|jpg|jpeg|gif)$/i,
// type: 'asset/resource',
// },
],
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm-bundler.js'
}
},
devServer: {
static: {
directory: path.join(__dirname, 'dist'),
},
host: '0.0.0.0',
port: 5555,
compress: true,
hot: true,
open: true,
}
};