2. css tree shaking

本文介绍了如何在Webpack中实现CSS的打包压缩、单独抽离以及Tree Shaking。使用css-loader加载并解析CSS文件,style-loader将CSS插入HTML中。通过mini-css-extract-plugin可以将CSS抽离到单独文件。为了进行CSS Tree Shaking,可以使用purifycss-webpack来移除未使用的样式。若涉及JS操作DOM,可能需要额外配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.打包压缩css文件

css-loader: 加载解析文件,如遇到@import会将相应的样式文件引入(如没有css-loader则不会引入该文件)

style-loader:将解析的css放style标签,插入head标签里

(css样式打包到main.js文件里)

实例:

/* demo.css*/
body{
    background: #ccc;
}

div{
    height: 200px;
    width: 200px;
    background: tomato;
}

p{
    font-size: 50px;
    font-weight: 800;
}

a{
    color: green;
}
//index.js
import './demo.css';

//webpack.config.js
module.exports = {
    module: {
        rules: [
            {
                test: /\.css$/,
                use: ['style-loader','css-loader']
            }
        ]
    }
}
<!-- index.html -->
    <div></div>
    <script src="./dist/main.js"></script>

 

2.单独抽离出css文件

mini-css-extract-plugin:将css抽离到单独的文件中

安装 npm install mini-css-extract-plugin --save-dev

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [MiniCssExtractPlugin.loader,'css-loader']
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin()
    ]
}

 

3.css-tree-shaking

purifycss-webpack:移除没有使用到css样式

安装 npm install purifycss-webpack purifycss --save-dev

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const PurifyCSSPlugin = require('purifycss-webpack');
const path = require('path');
const glob = require('glob')

module.exports = {
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [MiniCssExtractPlugin.loader,'css-loader']
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: '[name].css'
        }),
        new PurifyCSSPlugin({
            paths: glob.sync(path.join(__dirname, './*.html'))
        })
    ]
}

另:若在js文件中操作dom元素,则需另外配置,如

安装glob-all

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const PurifyCSSPlugin = require('purifycss-webpack');
const path = require('path');
const glob = require('glob-all');  

module.exports = {
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader']
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: '[name].css'
        }),
        new PurifyCSSPlugin({
            paths:
                glob.sync([
                    path.join(__dirname, './*.html'),
                    path.join(__dirname, './src/*.js')])
        })
    ]
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值