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

相关推荐
天宇&嘘月2 小时前
web第三次作业
前端·javascript·css
小王不会写code2 小时前
axios
前端·javascript·axios
luckyext4 小时前
HBuilderX中,VUE生成随机数字,vue调用随机数函数
前端·javascript·vue.js·微信小程序·小程序
小小码农(找工作版)4 小时前
JavaScript 前端面试 4(作用域链、this)
前端·javascript·面试
鱼樱前端5 小时前
深入JavaScript引擎与模块加载机制:从V8原理到模块化实战
前端·javascript
yangjiajia1234566 小时前
vue3 ref和reactive的区别
前端·javascript·vue.js
诚信爱国敬业友善6 小时前
Vue 基础二(进阶使用)
前端·javascript·vue.js
なし.6 小时前
【Web前端开发精品课 HTML CSS JavaScript基础教程】第二十四章课后题答案
前端·javascript·css·html
随风起舞17 小时前
node.js里的bind,apply, call的区别是什么
前端·javascript·node.js