简体   繁体   English

Webpack 将错误的图像加载到 dist 目录

[英]Webpack loads wrong images to dist directory

My webpack.config.js file我的webpack.config.js文件

const path = require('path');

const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
  entry: {
    index: './src/js/index.js',
  },

  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: 'html-loader',
            options: { minimize: true },
          },
        ],
      },
      {
        test: /\.(jpg|png)$/,
        use: {
          loader: 'url-loader',
        },
      },
      {
        test: /\.(css|scss)$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'postcss-loader',
          'sass-loader',
        ],
      },
    ],
  },

  output: {
    path: path.resolve(__dirname, './dist'),
    filename: './js/[name].bundle.js',
  },

  plugins: [
    new HtmlWebPackPlugin({
      template: path.resolve(__dirname, './src/index.html'),
      filename: 'index.html',
      chunks: ['index'],
    }),

    new CleanWebpackPlugin(),

    new MiniCssExtractPlugin({
      filename: './css/[name].css',
    }),

    new CopyWebpackPlugin({
      patterns: [{ from: './src/assets', to: './assets' }],
    }),
  ],

  devtool: 'source-map',
  mode: 'development',
};

my files structure where the problem occurs:我出现问题的文件结构:

在此处输入图像描述

what is strange, when I run npm run build in the terminal , all directories are loaded correctly I mean: background-image works, and slider directory with images is loaded, but there is also loaded some additional files with random numerical names奇怪的是,当我在terminal中运行npm run build时,所有目录都已正确加载我background-image有效,并且加载了带有图像的slider目录,但还加载了一些带有随机数字名称的附加文件

在此处输入图像描述

and those three additional .png files are loaded to my index.html as img1.png img2.png and img3.png files which not work on my website, they just do not want to load这三个额外的.png文件被加载到我的index.html作为img1.png img2.pngimg3.png文件在我的网站上不起作用,他们只是不想加载

I think your image files are probably double-processed, because you once just copy your assets folder to your dist output folder, and then you somewhere probably use the images with url("./someImage") or similar in your css files, which get processed by your css loader or css Mini Exctract plugin, which creates that cryptic image asset output, that then gets used in your html files, look at here: webpack.js.org/guides/asset-management/#loading-images.. I dont know why you need to copy your assets folder but that looks redundant to me...我认为你的图像文件可能是双重处理的,因为你曾经只是将你的资产文件夹复制到你的 dist output 文件夹,然后你可能会在你的 css 文件中使用带有url("./someImage")或类似的图像,其中get processed by your css loader or css Mini Exctract plugin, which creates that cryptic image asset output, that then gets used in your html files, look at here: webpack.js.org/guides/asset-management/#loading-images. .我不知道你为什么需要复制你的资产文件夹,但这对我来说看起来是多余的......

EDIT : I'm not an expert at this, but after investigating some hours into this weird error, I realized that the paths were set correctly to the image files, but the image output that file-loader or other loaders generate with the image (like 0f9b8be78d378ad2ef78.jpg) seems to be something different, if I open them in vscode editor in standard text/binary editor, I get this line: export default __webpack_public_path__ + "someimage.jpg";编辑:我不是这方面的专家,但在调查了这个奇怪的错误几个小时后,我意识到路径已正确设置为图像文件,但文件加载器或其他加载器生成的图像 output 与图像(像 0f9b8be78d378ad2ef78.jpg) 似乎有些不同,如果我在标准文本/二进制编辑器的 vscode 编辑器中打开它们,我会得到这一行: export default __webpack_public_path__ + "someimage.jpg"; , with url-loader its the binary64 converted string with data-url(..).. so it seems its not for the purpose to use it in static html files.. ,使用 url-loader 其二进制 64 转换字符串与 data-url(..).. 所以它似乎不是为了在 static html 文件中使用它。

I then used the recommended way to do it like this in webpack.config.js:然后我在 webpack.config.js 中使用了推荐的方法:

        {   test: /\.(jpg|png)$/, 
            type: 'asset/resource', }

after that my image was shown correctly, I have no idea what file-loader etc. is doing..之后我的图像正确显示,我不知道文件加载器等在做什么..

here is my final webpack.config.js:这是我的最终 webpack.config.js:

const path = require('path')

const HtmlWebPackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

module.exports = {
    entry: {
        index: './src/js/index.js',
    },
    devServer: {
        port: 5757,
        contentBase: path.resolve(__dirname, 'src'),
        publicPath: '/src',
    },

    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: ['babel-loader'],
            },
            {
                test: /\.html$/,
                use: [
                    {
                        loader: 'html-loader',
                        options: { minimize: true },
                    },
                ],
            },
            {
                test: /\.(jpg|png)$/,
                type: 'asset/resource',

            },
            {
                test: /\.(css|scss)$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    'postcss-loader',
                    'sass-loader',
                ],
            },
        ],
    },

    output: {
        path: path.resolve(__dirname, './build'),
        //publicPath: './assets/images',
    },

    plugins: [
        new HtmlWebPackPlugin({
            template: path.resolve(__dirname, './src/index.html'),
            filename: 'index.html',
            inject: 'body',
        }),

        new MiniCssExtractPlugin({
            filename: './css/[name].css',
        }),
    ],

    devtool: 'source-map',
    mode: 'development',
}

I have just solved my every problem because after using the answer from @ChillaBee , images were working correctly expect my background photo which I used in css file as url .我刚刚解决了我的所有问题,因为在使用@ChillaBee的答案后,图像工作正常,期望我在css文件中使用的background photourl Use the answer above but change使用上面的答案,但改变

{
    test: /\.(jpg|png)$/,
    type: 'asset/resource',
},

to

{
    test: /\.(jpg|png)$/,
    type: 'asset/inline',
},

now images from html and css are loaded correctly现在来自 html 和 css 的图像已正确加载

This is caused by Webpack 5's new Asset Modules .这是由 Webpack 5 的新资产模块引起的。 You can either remove url-loader and specify the asset type like so:您可以删除url-loader并指定资产类型,如下所示:

{
    test: /\.(jpg|png)$/,
    type: 'asset/inline',
},

Or you can disable asset modules by adding type: 'javascript/auto' to your rule:或者您可以通过在规则中添加type: 'javascript/auto'来禁用资产模块:

{
  test: /\.(jpg|png)$/,
  use: {
    loader: 'url-loader',
  },
  type: 'javascript/auto'
}

See the documentation to learn more, and to see how to do this for file-loader and raw-loader as well.请参阅文档以了解更多信息,并了解如何对file-loaderraw-loader器执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM