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类名? 有空再探讨

相关推荐
贩卖黄昏的熊5 分钟前
typescript 快速入门
开发语言·前端·javascript·typescript·ecmascript·es6
Syron1 小时前
ScaleSlider 组件实现
javascript
xhxxx1 小时前
深入执行上下文:JavaScript 中 this 的底层绑定机制
javascript
DsirNg2 小时前
Vue 3:我在真实项目中如何用事件委托
前端·javascript·vue.js
克喵的水银蛇2 小时前
Flutter 适配实战:屏幕适配 + 暗黑模式 + 多语言
前端·javascript·flutter
冬男zdn2 小时前
Next.js 16 + next-intl App Router 国际化实现指南
javascript·typescript·reactjs
有意义2 小时前
this 不是你想的 this:从作用域迷失到调用栈掌控
javascript·面试·ecmascript 6
风止何安啊3 小时前
别被 JS 骗了!终极指南:JS 类型转换真相大揭秘
前端·javascript·面试
拉不动的猪3 小时前
深入理解 Vue keep-alive:缓存本质、触发条件与生命周期对比
前端·javascript·vue.js
over6973 小时前
深入理解 JavaScript 原型链与继承机制:从 instanceof 到多种继承模式
前端·javascript·面试