任何类型的路径都将转换为以斜线开头的路径,例如 /img/1.jpg。因此,所有路径都不起作用,我在控制台中看到一个错误:“ERR_FILE_NOT_FOUND”,如果用 ./ 替换路径的开头,那么一切正常。朋友们!请帮助解决这个问题。
// index.js
import './index.html'
import './index.scss'
// webpack.config.js
context: path.resolve(__dirname, 'src'),
entry: ['./index.js'],
output: {
filename: '[hash].js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/',
},
plugins: [
new HtmlWebpackPlugin({
template: './index.html',
minify: isProd,
}),
new CleanWebpackPlugin(),
new MiniCssExtrackPlugin({
filename: '[hash].css'
})
],
devServer: {
port: 3000,
hot: isDev,
historyApiFallback: true
},
optimization: optimization(),
module: {
rules: [
{
test: /.js$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /.html$/,
loader: 'html-loader',
options: {
attributes: {
root: '.',
}
}
},
{
test: /.scss$/,
use: [
{
loader: MiniCssExtrackPlugin.loader,
options: {
hmr: isDev,
reloadAll: true,
},
},
'css-loader',
'sass-loader',
],
},
{
test: /.(png|svg|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[hash].[ext]',
outputPath: './img',
useRelativePath: true
}
},
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
progressive: true,
quality: 75
}
}
}
]
},
根据 webpack 的 publicPath 输出配置中的值设置路径的开头。
如果您拥有 baseUrl 级别的所有资产,请留下斜线。如果它们相对于当前目录 - 指定 ./