由于某种原因,我的Webpack配置正在加载来自SCSS文件的图像,而不是加载来自HTML文件的图像。另外,当我运行BUILD命令以交付产品存档时,它不会创建“ img”文件夹。坦白地说,我是webpack 4的新手,我想我要在WP配置文件中添加几个步骤。
这是我的webpack.dev.js
这是我要创建的prod文件夹结构:
dist
| ---- img
| ---- css
| ---- js
a.html
b.html
c.html
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
module.exports = {
entry: {
main: "./src/js/scripts.js"
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "js/[name].[hash].js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.scss$/,
use: [
"style-loader",
MiniCssExtractPlugin.loader,
"css-loader",
"postcss-loader",
"sass-loader"
]
},
{
test: /\.(png|jpg|gif)$/,
use: ["url-loader"]
}
]
},
devServer: {
port: 8080
},
plugins: [
new CleanWebpackPlugin("dist", {}),
new MiniCssExtractPlugin({
filename: "css/style.[contenthash].css"
}),
new HtmlWebpackPlugin({
template: "./src/index.html",
inject: false,
hash: true,
filename: "index.html"
}),
new HtmlWebpackPlugin({
template: "./src/actualitat.html",
inject: false,
hash: true,
filename: "actualitat.html"
}),
new HtmlWebpackPlugin({
template: "./src/projectes.html",
inject: false,
hash: true,
filename: "projectes.html"
})
]
};
这是在我的html文件中同时加载css和js的方式:
<link
rel="stylesheet"
href="<%=htmlWebpackPlugin.files.chunks.main.css %>"
/>
<script src="<%= htmlWebpackPlugin.files.chunks.main.entry %>"></script>
我有一个“ scripts.js” js文件,我在其中导入了这样的文件:
import "../scss/style.scss";
import "../img/searchBar-icon.png";
import "../img/townHall.png";
import "../img/icon-title.png";
更新:
我更改了使用“文件加载器”加载器加载图像的方式:
{
test: /\.(png|jpg|gif)$/,
use: {
loader: "file-loader",
options: {
outputPath: "img/",
name: "[name][hash].[ext]"
}
}
}
现在我所有的图像都被复制到“ img”文件夹,这很好,问题是文件的所有名称现在都具有哈希值(这很有意义,因为我告诉加载程序要添加它们)并且它们没有加载我的html文件。
答案 0 :(得分:0)
您可以尝试以下方法来加载图像吗?
{
test: /\.(jpe?g|png|gif|ico)$/i,
use: ["file-loader?name=[name].[hash].[ext]"]
}