0

我正在从 gulp 过渡到 webpack,我在一个static/img文件夹中有图像,我想处理这些图像image-webpack-loader,然后复制到一个build/public/img文件夹中。file-loader我想用这个吗?问题是图像没有被复制。事实上,这个加载器似乎在构建过程中被忽略了。

const ExtractTextPlugin = require('extract-text-webpack-plugin');
const path = require('path');

module.exports = {
  context: path.resolve(__dirname, 'static'),
  entry: ['./js/frontend.js','./sass/app.scss'],
  output: {
    path: path.join(__dirname, 'build/public'),
    filename: 'js/frontend.js'
  },
  module: {
    rules: [
      {
        test: /\.(jpe?g|png|gif|svg)$/,
        loader: [
            'file-loader?name=img/[name].[ext]',
            'image-webpack-loader?bypassOnDebug&optimizationLevel=7&interlaced=false'
        ]
      },
      {
        test: /\.(sass|scss)$/,
        loader: ExtractTextPlugin.extract({
          use: [{
            loader: 'css-loader',
            options: {
              sourceMap: true
            }
          },
          {
            loader: 'sass-loader',
            options: {
              sourceMap: true
            }
          }]
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin({ 
      filename: 'css/styles.css',
      allChunks: true
    })
  ],
  devtool: 'source-map'
};
4

2 回答 2

1

如果您在某处不需要图像,Webpack 不知道它们存在并且不会处理它们。

将以下代码放入./js/frontend.js其中以强制 Webpack 要求static/img文件夹中的每个资产:

// load assets
function requireAll(r) { r.keys().forEach(r); }
requireAll(require.context('img/', true));
于 2017-08-03T13:49:59.453 回答
0

我不确定这是解决方案还是解决方法,但我所做的是使用CopyWebpackPluginwith ImageminPlugin

const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ImageminPlugin = require('imagemin-webpack-plugin').default;
const path = require('path');

module.exports = {
  context: path.resolve(__dirname, 'static'),
  entry: ['./js/frontend.js','./sass/app.scss'],
  output: {
    path: path.join(__dirname, 'build/public'),
    filename: 'js/frontend.js'
  },
  module: {
    rules: [
      {
        test: /\.(sass|scss)$/,
        loader: ExtractTextPlugin.extract({
          use: [{
            loader: 'css-loader',
            options: {
              sourceMap: true
            }
          },
          {
            loader: 'sass-loader',
            options: {
              sourceMap: true
            }
          }]
        })
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin('build/public'),
    new ExtractTextPlugin({ 
      filename: 'css/styles.css',
      allChunks: true
    }),
    new CopyWebpackPlugin([
      {
        from: 'img', to: 'img'
      }
    ]),
    new ImageminPlugin({ test: /\.(jpe?g|png|gif|svg)$/i })
  ],
  devtool: 'source-map'
};
于 2017-08-03T13:25:21.510 回答