blog icon indicating copy to clipboard operation
blog copied to clipboard

处理IE9不支持webpack打包后体积依然过大的css文件

Open xianzou opened this issue 5 years ago • 0 comments

​ 目前都很流行webpack打包,但是引入样式过多,很容易导致打包出来的样式文件过大,然而IE9对样式表却有限制,具体如下:

KB 262161 概述了Internet Explorer 6至9支持的样式表和规则的最大数量:

  • A sheet may contain up to 4095 rules

    样式规则最多只能有4095个,多于这个数目的会被忽略,这里应该是指选择器

  • A sheet may @import up to 31 sheets

    样式表(通过@import, <link> 或 <style>)最多可以有31个(总和),多于这个数目的会被忽略

  • @import nesting supports up to 4 levels deep

    @import最多可以嵌套3层,多于3层的将被忽略

针对这种情况开发和生产环境都需要处理。

生产环境:

使用对应的插件对大尺寸的css再分割:css-split-webpack-plugin

安装:

yarn add css-split-webpack-plugin -D;
or 
npm i css-split-webpack-plugin -D;

在webpack.prod.config.js中使用:

const CSSSplitWebpackPlugin = require('css-split-webpack-plugin').default;

module.exports = {
    entry:...,
    devtool: 'cheap-module-source-map',
    plugins:[
    	new CSSSplitWebpackPlugin({
            size: 3800, //默认值4000
            filename: 'css/[name]-[part].[ext]'
        }),
        ...
    ],
    ...
};

执行yarn build编译,在build后在文件夹下的css目录可以看到对应切割的样式文件,然后可以启动http-server进行IE9下的预览。

开发环境

开发环境下一般会将样式使用style标签注入到head中,这里不使用css-split-webpack-plugin,如果你的style-loader版本低于1X(最新的版本已经废弃singleton这个参数),那么可以尝试使用如下方式:

webpack.dev.config.js

modeule.exports = {
    ...
    rules:[
        test: /\.css$/,
        use: [{
                loader: 'style-loader',
                options: { singleton: false } //不把css放入到一个style标签内
   		 },
        {
            loader: 'css-loader'
        }]
    ],
    ....
}

运行yarn start之后,打开IE9可以看到head标签下会生成很多style标签;

xianzou avatar Sep 24 '19 07:09 xianzou