我的 webpack 和 pug 配置有问题。图像未显示(我收到 404 错误)
这是:webpack.common.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const __ROOT__ = process.cwd();
const fs = require("fs");
let templates = [];
let dir = "src";
let files = fs.readdirSync(dir);
files.forEach((file) => {
if (file.match(/\.pug$/)) {
let filename = file.substring(0, file.length - 4);
templates.push(
new HtmlWebpackPlugin({
template: dir + "/" + filename + ".pug",
filename: filename + ".html",
hash: true,
})
);
}
});
module.exports = {
entry: path.resolve(__ROOT__, "src/js/index.js"),
output: {
path: path.resolve(__ROOT__, "build"),
filename: "js/[name].bundle.js",
chunkFilename: "js/[name].chunk.js",
},
plugins: [new CleanWebpackPlugin(), ...templates],
module: {
rules: [
{
test: /\.pug$/,
use: [
{ loader: "raw-loader" },
{
loader: "pug-html-loader",
options: {
pretty: true,
},
},
],
},
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
cacheDirectory: true,
configFile: path.resolve(__ROOT__, "config/babel.config.js"),
},
},
},
{
test: /\.(?:ico|gif|png|jpg|jpeg|webp|svg)$/i,
loader: "file-loader",
options: {
name: "[path][name].[ext]",
context: "src", // prevent display of src/ in filename
},
},
],
},
};
下一个文件 webpack.dev.js:
const {
merge
} = require("webpack-merge");
const commonConfig = require("./webpack.config.common");
module.exports = merge(commonConfig, {
mode: "development",
devtool: "inline-source-map",
devServer: {
contentBase: "./build",
compress: true,
port: 3001,
overlay: true,
},
module: {
rules: [{
test: /\.css$/,
use: ["style-loader", "css-loader"],
}, ],
rules: [{
test: /\.s[ac]ss$/,
use: ["style-loader", "css-loader", "sass-loader"],
}, ],
},
});
最后是哈巴狗索引页面:我尝试了多个 url,它们都不起作用。
html
head
title Webpack 4
body
h1 Project starter
hr
img(src='images/logo.png')
img(src='./images/logo.png')
img(src='../images/logo.png')
img(src='../../images/logo.png')