webpack tree shaking示例: js css

JS tree shaking

生成环境下,会自动开启tree shaking,用来清除没有用到的js代码

{
	mode: 'production',
}

CSS tree shaking

需要借助purgecss-webpack-plugin来清楚未用到的css。

一: 原生的css tree shaking

src/index.js
import './index.css'

const button = document.createElement('button')
button.style.width = '200px'
button.style.height = '200px'
button.innerText = '动态加载js'
button.addEventListener('click', () => {
    import('./other.js').then(res => {
        console.log('加载了js')
    })
})
document.body.appendChild(button)
src/index.css

.addd {
    color: pink;
}
.unused2 {
    color: blue;
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    Document
    <div class="addd">dddd</div>
</body>
</html>
webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');  
const { PurgeCSSPlugin } = require("purgecss-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); 
const path = require('path');  
const glob = require('glob');  

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'main.js',
    },
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader'
        ]
      },
    ]
  },
  plugins: [
    new MiniCssExtractPlugin(),
        new PurgeCSSPlugin({
      // 用来告诉PurgeCSS哪些文件可能包含CSS类名的引用
      paths: glob.sync(path.join(__dirname, 'index.html')), // 匹配所有 .vue 和 .js 文件   
    }),
    new HtmlWebpackPlugin({
        template: './index.html',
    }),

  ]
}

二: vue的css tree shaking

不借助vue-cli怎么做到移除单文件里面未用的css类名? 有空再探讨

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值