Webpack文件加载程序输出空图像



我联系您是因为我的webpack配置遇到问题。我只想从/src/images/将我的图像复制到/dist/images/文件夹中。

这是我的架构:

dist
|-images
| |-lorem-picsum.png
|-pages
| |--about.html
| |--home.html
|-a069f3e2cf7332c2cd34.png
|-main.js
node_modules
src
|-images
| |-lorem-picsum.png
|-pages
| |--about.html
| |--home.html
|-index.js
package-lock.json
package.json
webpack.config.js

我正在使用文件加载器,这是我的webpack.config.js:的配置

const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
mode: 'development',
entry: path.resolve(__dirname, './src/index.js'),
output: {
path: path.resolve(__dirname, './dist'),
filename: 'main.js',
},
module: {
rules: [
{
test: /.html$/i,
loader: "html-loader",
options : {
minimize : false,
}
},
{
test: /.(png|jpe?g|gif|svg)$/i,
use: [
{
loader: 'file-loader',
options: {
name : '[name].[ext]',
outputPath: 'images'
}
}
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template : path.resolve(__dirname, './src/pages/home.html'),
filename: path.resolve(__dirname, './dist/pages/home.html'),
}),
new HtmlWebpackPlugin({
template : path.resolve(__dirname, './src/pages/about.html'),
filename: path.resolve(__dirname, './dist/pages/about.html'),
})
],
};

当我启动";npm运行构建";,它正在dist文件夹中创建一个空图像(a069f3e2cf7332cd34.png(。此图像没有视觉内容,但包含以下文本:

export default __webpack_public_path__ + "images/lorem-picsum.png";

和/dist/home.html现在包含:

<img src="../a069f3e2cf7332c2cd34.png" alt="">

但是图像并没有显示在正面。

你知道我怎样才能避免创造这个";"空";文件,然后简单地将我的图像文件夹复制到dist中,并保持与/src/folder中所写的相同?

提前感谢

解决方案:

问题是版本5中的Webpack不能像这样处理图像。

现在不需要"文件加载器",您只需在webpack.config.js:中使用以下规则即可

{
test: /.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
generator: {
filename: 'images/[name][ext]'
}
}

这些行将在/dist/images/中构建相同的图像

最新更新