webpack tree shaking示例: js css

JS tree shaking

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

c 复制代码
{
	mode: 'production',
}

CSS tree shaking

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

一: 原生的css tree shaking

c 复制代码
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)
c 复制代码
src/index.css

.addd {
    color: pink;
}
.unused2 {
    color: blue;
}
c 复制代码
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>
c 复制代码
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类名? 有空再探讨

相关推荐
孤水寒月4 小时前
基于HTML的悬窗可拖动记事本
前端·css·html
脑袋大大的5 小时前
JavaScript 性能优化实战:减少 DOM 操作引发的重排与重绘
开发语言·javascript·性能优化
速易达网络6 小时前
RuoYi、Vue CLI 和 uni-app 结合构建跨端全家桶方案
javascript·vue.js·低代码
耶啵奶膘6 小时前
uniapp+firstUI——上传视频组件fui-upload-video
前端·javascript·uni-app
JoJo_Way6 小时前
LeetCode三数之和-js题解
javascript·算法·leetcode
视频砖家7 小时前
移动端Html5播放器按钮变小的问题解决方法
前端·javascript·viewport功能
GISer_Jing10 小时前
Monorepo+Pnpm+Turborepo
前端·javascript·ecmascript
天涯学馆10 小时前
前端开发也能用 WebAssembly?这些场景超实用!
前端·javascript·面试
我在北京coding11 小时前
TypeError: Cannot read properties of undefined (reading ‘queryComponents‘)
前端·javascript·vue.js