Webpack:将css提取到自己的bundle中

时间:2017-11-14 15:52:21

标签: css webpack babel

我在项目中使用webpack。我使用样式加载器,所以我可以import "my.css"

css与javascript捆绑在一起,当组件挂载时,它将在<style>标记中呈现,确定。

但是,我想保留该导入语法,并使webpack为每个入口点构建一个css包。

因此,webpack输出应为[name].bundle.js AND [name].bundle.css。 这是我能做到的吗?

var config = {
  entry: {
    'admin': APP_DIR + '/admin.entry.jsx',
    'public': APP_DIR + '/public.entry.jsx'
  },
  output: {
    path: BUILD_DIR,
    filename: '[name].bundle.js'
  },
  resolve: {
    extensions: ['.js', '.jsx', '.json']
  },
  plugins: [],
  devtool: 'cheap-source-map',
  module: {
    loaders: [{
        test: /(\/index)?\.jsx?/,
        include: APP_DIR,
        loader: 'babel-loader'
      },
      {
        test: /\.scss$/,
        loaders: [
          'style-loader',
          'css-loader',
          'sass-loader',
          {
            loader: 'sass-resources-loader',
            options: {
              resources: ['./src/styles/constants.scss']
            },
          }
        ]
      }
    ],
  }
};

以及这个babel.rc:

{
  "presets" : ["es2015", "react"],
  "plugins": ["transform-decorators-legacy", "babel-plugin-root-import"]
}

1 个答案:

答案 0 :(得分:1)

是的,您需要使用extract-text-webpack-plugin。您可能只想在生产配置上执行此操作。 Config看起来像这样:

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

module.exports = {
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          //resolve-url-loader may be chained before sass-loader if necessary
          use: ['css-loader', 'sass-loader']
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin('style.css')
    //if you want to pass in options, you can do so:
    //new ExtractTextPlugin({
    //  filename: 'style.css'
    //})
  ]
}