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

栏目: CSS · 发布时间: 4年前

内容简介:上节:懒加载上节目录如下:

目录

上节:懒加载

上节目录如下:

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

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:

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

现在样式是通过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:

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

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

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

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

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

下节:shiming(待更新)


以上所述就是小编给大家介绍的《webpack4.29.x成神之路(十九) css代码分割》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Linux Command Line

The Linux Command Line

William E. Shotts Jr. / No Starch Press, Incorporated / 2012-1-17 / USD 39.95

You've experienced the shiny, point-and-click surface of your Linux computer-now dive below and explore its depths with the power of the command line. The Linux Command Line takes you from your very ......一起来看看 《The Linux Command Line》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

SHA 加密
SHA 加密

SHA 加密工具