如何使用MiniCssExtractPlugin从style.css中拆分CSS?

时间:2019-09-17 19:05:32

标签: webpack sass mini-css-extract-plugin

我正在尝试将我的两个.scss文件转换为两个不同的.css文件:一个叫做timer_player.css,另一个叫做style.css

style.css不能具有timer_player.css的任何样式。

使用ExtractTextPlugin,我可以通过创建两个实例来实现此目的,但是不建议使用此包。

我的文件夹树看起来像这样:

- src
  - js
    - popup.js
    - content_scripts
      - timer_player
        - index.js
  - css
    - popup.css
    - timer_player.css

1 个答案:

答案 0 :(得分:0)

在仔细阅读了此Issue之后,我才能够做到这一点。诀窍的一部分是使用optimization属性并按块名称进行过滤。

我的webpack.config.js现在看起来像这样:

module.exports = {
  entry: {
    popup: ['./src/js/popup.js', './src/css/popup.scss'],
    timer_player: [
      './src/js/content_scripts/timer_player/index.js',
      './src/css/timer_player.scss',
    ],
  },
  output: {
    publicPath: '.',
    path: resolve(__dirname, 'dist/'),
    filename: '[name].js',
    libraryTarget: 'umd',
  },
  plugins: [
    new WebpackReloaderPlugin({
      port: 9090, // Which port use to create the server
      reloadPage: true, // Force the reload of the page also
      entries: {
        // The entries used for the content/background scripts
        contentScript: 'popup', // Use the entry names, not the file name or the path
        background: 'background', // *REQUIRED
      },
    }),

    new MiniCssExtractPlugin({ filename: '[name].css' }),
    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'src', 'popup.html'),
      filename: 'popup.html',
      chunks: ['popup'],
    }),
    new CopyWebpackPlugin([
      { from: './src/manifest.json' },
      { from: './src/images', to: 'images' },
    ]),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
    }),
  ],
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.scss$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader', // translates CSS into CommonJS
          {
            loader: 'sass-loader',
            options: {
              includePaths: ['node_modules', 'node_modules/@material/*']
                .map(d => path.join(__dirname, d))
                .map(g => glob.sync(g))
                .reduce((a, c) => a.concat(c), []),
            },
          },
        ],
      },
      {
        test: /\.txt$/,
        use: 'raw-loader',
      },
    ],
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        extractPopupStyles: {
          name: 'style',
          chunks: chunk => chunk.name === 'popup',
        },
      },
    },
  },
};

欢迎提出任何建议