为什么Webpack文件加载器不触发CSS URL?

时间:2018-11-10 02:59:19

标签: javascript css webpack webpack-4 webpack-file-loader

我正试图让Webpack吸收从.scss文件引用的图像文件。但是,我尝试过的所有操作似乎都没有触发文件加载器。我们的CSS被很好地捆绑在一起,但是CSS中的所有url()引用似乎都没有被修改过,并且没有图像文件被发出。

请参阅下面的示例sass和当前的webpack配置。我可以验证文件扩展名regex是否正确,并且更改加载程序的顺序似乎没有任何效果。还需要其他步骤来确保文件加载器看到CSS中的网址吗?

  #hero {
    background-image: url('/assets/welcome/responsive/header-image.jpg');
    background-size: cover;
    background-position: 0% 70%;
    min-height: 435px;
    background-color: #000;
    color: $white;
    font-weight: 200;
    position: relative;
}

const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
  entry: {
    'public/compiled/app': './app/assets/javascripts/compile/application.js',
    'public/compiled/seo_srp_map_sections':
      './app/assets/javascripts/compile/seo_srp_map_sections.js',
    'app/assets/javascripts/server_rendering':
      './app/assets/javascripts/server_rendering_to_compile.js'
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, '.')
  },
  resolve: {
    alias: {
      templates: path.resolve(__dirname, 'app/assets/javascripts/templates'),
      stylesheets: path.resolve(__dirname, 'app/assets/stylesheets'),
      vendor_stylesheets: path.resolve(__dirname, 'vendor/assets/stylesheets')
    }
  },
  plugins: [
    new webpack.ProvidePlugin({
      jQuery: 'jquery'
    }),
    new MiniCssExtractPlugin({
      filename: '[name].css'
    })
  ],
  module: {
    rules: [
      {
        test: /\.ejs$/,
        loader: 'ejs-loader'
      },
      {
        test: /\.m?jsx?$/,
        use: {
          loader: 'babel-loader'
        }
      },
      {
        test: /\.s?css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
      },
      {
        test: /\.(png|woff|woff2|eot|ttf|svg|jpg)$/,
        loader: 'file-loader'
      }
    ]
  }
};

1 个答案:

答案 0 :(得分:-1)

您可以像这样添加MiniCssExtractPlugin:

 plugins: [
    new MiniCssExtractPlugin({
      filename: "style.css",
      chunkFilename: "style.chunk.css",
      hot: true,
      orderWarning: true,
      reloadAll: true,
      cssModules: true
    })
]

对于图像类型,您可以尝试使用url-loader

  {
    test: /\.(png|svg|jpg|gif)$/,
    use: [
      {
        loader: 'url-loader',
        options: {
          limit: 5000
        }
      }
    ]
  }

对于svg,您可以使用加载程序的字体格式为file-loader