简体   繁体   English

Webpack 的文件加载器在生产过程中不会将图像从 /src 复制到 /dist

[英]Webpack's file loader doesn't copy images during production from /src to /dist

I have a Webpack setup which is split into 2 config files:我有一个 Webpack 设置,它分为 2 个配置文件:

webpack.config.js handles the development portion which is fired using npx webpack-dev-server and webpack.config.prod.js respectively which handles the production by typing npm run build . webpack.config.js处理分别使用npx webpack-dev-serverwebpack.config.prod.js触发的开发部分,它们通过键入npm run build来处理生产。

The development config works as expected, but the production one has one problem: everything works fine, but the images aren't copied and optimized from the source folder: src/images/sm , src/images/bg to dist/images/sm , dist/images/bg .开发配置按预期工作,但生产配置有一个问题:一切正常,但图像没有从源文件夹复制和优化: src/images/sm , src/images/bgdist/images/sm , dist/images/bg

webpack.prod.js webpack.prod.js

const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const path = require('path');

module.exports = function(){
  return {
    mode: 'development',
    entry: [
      './src/app.js'
    ],
    watch: true,
    watchOptions: {
      aggregateTimeout: 300, // Process all changes which happened in this time into one rebuild
      poll: 1000, // Check for changes every second,
      ignored: /node_modules/,
      // ignored: [
      //   '**/*.scss', '/node_modules/'
      // ]
    },
    devtool: 'source-maps',
    devServer: {
      contentBase: path.join(__dirname, 'src'),
      watchContentBase: true,
      host: '0.0.0.0',
      hot: true,
      open: true,
      inline: true,
      port: 9000
    },
    plugins: [
      new HtmlWebpackPlugin({
        title: 'Webpack starter project',
        template: path.resolve('./src/index.pug')
      }),
      new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery"
      }),
      new webpack.HotModuleReplacementPlugin()
    ],
    module: {
      rules: [
        {
          test: /\.pug$/,
          use: ['raw-loader', 'pug-html-loader'],
        },
        {
          test: /\.scss$/,
          use: [
            'style-loader',
            "css-loader",
            "sass-loader"
          ]
        },
        {
          test: /\.(jpg|jpeg|gif|png|svg|webp)$/,
          use: [
            {
              loader: "file-loader",
              options: {
                outputPath: './images',
                name: "[name].[ext]",
              },
            },
          ]
        },
        {
          test: /\.html$/,
          use: {
            loader: 'html-loader',
          }
        },
      ]
    }
  };
}

webpack.config.prod.js webpack.config.prod.js

const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const path = require('path');

module.exports = function(){
  return {
    mode: 'production',
    entry: [
      './src/app.js'
    ],
    optimization: {
      minimizer: [
        new OptimizeCSSAssetsPlugin()
      ]
    },
    plugins: [
      new CleanWebpackPlugin(),
      new HtmlWebpackPlugin({
        title: 'Webpack starter project',
        filename: 'index.html',
        template: path.resolve('./src/index.pug')
      }),
      new MiniCssExtractPlugin({
        filename: '[name].css',
        chunkFilename: '[id].css'
      }),
      new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery"
      }),
      new webpack.HotModuleReplacementPlugin()
    ],
    module: {
      rules: [
        {
          test: /\.pug$/,
          use: ['raw-loader', 'pug-html-loader'],
        },
        {
          test: /\.scss$/,
          use: [
            MiniCssExtractPlugin.loader,
            "css-loader",
            "sass-loader"
          ]
        },
        {
         test: /\.(jpg|jpeg|gif|png|svg|webp)$/,
         use: [
           {
             loader: "file-loader",
             options: {
               outputPath: './images',
               name: "[name].[ext]",
             },
           },
           {
             loader: 'image-webpack-loader',
             options: {
               bypassOnDebug: true,
               mozjpeg: {
                 progressive: false,
                 quality: 45
               },
               // optipng.enabled: false will disable optipng
               optipng: {
                 enabled: true,
               },
               pngquant: {
                 quality: '65-90',
                 speed: 4
               },
               gifsicle: {
                 interlaced: true,
                 optimizationLevel: 3
               },
               // the webp option will enable WEBP
               webp: {
                 quality: 20
               }
             }
           },
         ],
       },
        {
          test: /\.html$/,
          use: {
            loader: 'html-loader',
          }
        },
      ]
    }
  };
}

I uploaded my webpack setup to Google Drive and if anybody wants to check it out, here it is.我将我的 webpack 设置上传到了 Google Drive,如果有人想查看它,就在这里 I googled all day and I don't see anything wrong with my code.我用谷歌搜索了一整天,我没有发现我的代码有什么问题。 I tried other webpack configs and they have the same code as mine and their images get copied in the dist folder.我尝试了其他 webpack 配置,它们的代码与我的相同,并且它们的图像被复制到 dist 文件夹中。 Can anyone help me figure this out?谁能帮我解决这个问题?

Somebody on Reddit helped me. Reddit 上有人帮助了我。 All I had to do was import the images in the app.js.我所要做的就是在 app.js 中导入图像。 Strangely, using other configs never required me to import the images, but I think that's because those configs were built using an older version of file loader.奇怪的是,使用其他配置从来不需要我导入图像,但我认为这是因为这些配置是使用旧版本的文件加载器构建的。

I also changed the quality property since webpack expects an array instead of a string.我还更改了 quality 属性,因为 webpack 需要一个数组而不是字符串。

pngquant: {
  quality: [0.65, 0.90],
  speed: 4
}

To generate images in the dist folder under the same tree scheme as in the src I had to change this part :要在与 src 相同的树方案下在 dist 文件夹中生成图像,我必须更改此部分:

{
  loader: "file-loader",
    options: {
        name: "[path]/[name].[ext]",
        context: "src"
    },
},

Try with copy-webpack-plugin.尝试使用 copy-webpack-plugin。 It worked for me.它对我有用。 I tried to like this.我试着喜欢这个。

First, you need to install the copy-webpack-plugin module.首先,您需要安装 copy-webpack-plugin 模块。

npm install copy-webpack-plugin --save-dev npm install copy-webpack-plugin --save-dev

In webpack.config.js:在 webpack.config.js 中:

const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports={
 plugins: (
   new CopyWebpackPlugin({
        patterns: [
          {from: "src/images", to: "images/"}
        ],
      }),
   )
}

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

相关问题 如何使用Webpack将脚本文件从src复制到dist - How to copy script files from src to dist using webpack 如何使用文件加载器在 dist 中以相同的方式重复和复制 src 目录路径? - How to repeat and copy src directories path in the same way in dist with file-loader? 如何使用复制文件 npm 模块将所有图像从 src 文件夹递归复制到 dist 文件夹? - How to copy all images from a src folder to a dist folder recursively using copy files npm module? Webpack 的文件加载器不会更新 HTML 文件中资产的路径 - Webpack's file loader doesn't update path to the assets in the HTML file Webpack不会从ng-src中的给定路径加载图像 - Webpack doesn't load images from given path in ng-src Webpack 文件加载器不适用于图像。 创建 curropted 文件和 img src 指向该文件 - Webpack file-loader not working for images. Creating curropted file and img src is pointed to that file Webpack URL加载器上的某些图像上的404s - 404s on some images from Webpack url-loader 反应:Webpack文件加载器无法正确加载 - React: webpack file loader doesn't loads correctly 图像不在生产版本中显示,仅在开发中显示(webpack/sass-loader) - Images not displaying on production build, only in dev (webpack/sass-loader) Webpack文件加载器未导出图像 - Webpack file-loader not exporting images
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM