webpack4.29.x成神之路(十九) css代码分割

1

目录

上节: 懒加载

上节目录如下:

clipboard.png

css代码分割一般用于生产环境,先修改src/index.js:

import './styles/index.less';
import _ from 'lodash';

const root = document.getElementById('root');
root.innerText = _.join(['hello', 'webpack']);

styles/index.less:

#root{
  color: blue;
}

然后npm run build,浏览器运行bundles/index.html:

clipboard.png

现在样式是通过style标签内联在页面上的。

现在修改配置,让样式通过link标签外部引入:
webpack/webpack.prod.js:

const CleanWebpackPlugin = require('clean-webpack-plugin');
const merge = require('webpack-merge');
const baseConfig = require('./webpack.base');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = merge(baseConfig, {
  mode: 'production',
  output: {
    filename: '[name].[contenthash:10].js'
  },
  devtool: 'cheap-module-source-map',
  module: {
    rules: [{
      test: /\.less$/,
      use: [{
        loader: MiniCssExtractPlugin.loader,
      }, 'css-loader', 'postcss-loader', 'less-loader']
    }]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].css',
      chunkFilename: '[id].css'
    }),
    new CleanWebpackPlugin()
  ],
  optimization: {
    splitChunks: {
      chunks: 'all'
    }
  }
});

安装mini-css-extract-plugin:npm i mini-css-extract-plugin -D

然后打包npm run build:

clipboard.png

生成了单独的css文件,浏览器运行bundles/index.html, 打开f12:

clipboard.png

这样就实现了link的外部引入

详细配置参考:https://webpack.js.org/plugin...

下节:编写一个loader


如果觉得我的文章对你有用,请随意赞赏

你可能感兴趣的

载入中...