webpack 4.0 分离css文件

936 阅读1分钟
使用webpack4.0分离css,使用的插件:
npm i -D mini-css-extract-plugin
npm i -D postcss-loader
npm i -D autoprefixer

1.起步

在公用webpack配置中配置rules,使用 MiniCssExtractPlugin.loader替代style-loader:
// .....
const devMode = process.env.NODE_ENV !== 'production';
// ....
const config = {
    module: {
        rules: [
          {
            test: /\.scss$/,
            use: [
              {
                loader: MiniCssExtractPlugin.loader,
                options: {
                  // you can specify a publicPath here
                  // by default it uses publicPath in webpackOptions.output
                  publicPath: '../',
                  hmr: devMode
                }
              },
              {
                loader: 'css-loader',
                options: {
                  importLoaders: 2, // 向前两个loader,确保都加上前缀
                  modules: true
                }
              },
              'postcss-loader',
              'sass-loader'
            ]
          }
            // ...
        ]
    },
    plugins: [
    	 new MiniCssExtractPlugin({
          // Options similar to the same options in webpackOptions.output
          // all options are optional
          filename: 'statics/css/[name].[contentHash:6].css',
          chunkFilename: '[id].css',
          ignoreOrder: false // Enable to remove warnings about conflicting order
    	}),
    ]
}

2.配置postcss-loader

配置postcss-loader 和 autoprefixer插件,给样式加上厂商前缀。
  • 新建postcss.config.js文件,作为postcss-loader配置参数,引入autoprefixer插件
module.exports = {
  plugins: [require('autoprefixer')]
};
  • 配置autoprefixer,在package.json中加入以下代码
"browserslist": {
    "production": [
      "last 4 version" // 根据不同需求配置前缀需求
    ],
    "development": [
      "last 4 version"
    ]
  }

3.测试结果

div {
  box-sizing: border-box;
  transition: all 0.3s linear;
  transform: rotate(80deg);
  user-select: none;
  color: green($color: #000000);
  background: linear-gradient(to bottom, white, black);
}

输出: main.venders.css

div {
  -webkit-box-sizing: border-box;
          box-sizing: border-box;
  -webkit-transition: all 0.3s linear;
  -o-transition: all 0.3s linear;
  transition: all 0.3s linear;
  -webkit-transform: rotate(80deg);
      -ms-transform: rotate(80deg);
          transform: rotate(80deg);
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
  color: 0;
  background: -webkit-gradient(linear, left top, left bottom, from(white), to(black));
  background: -o-linear-gradient(top, white, black);
  background: linear-gradient(to bottom, white, black); }