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

相关推荐
@大迁世界1 小时前
Vue 设计模式 实战指南
前端·javascript·vue.js·设计模式·ecmascript
jump_jump2 小时前
妙用 localeCompare 获取汉字拼音首字母
前端·javascript·浏览器
U.2 SSD2 小时前
Echarts单轴坐标系散点图
前端·javascript·echarts
不做无法实现的梦~2 小时前
jetson刷系统之后没有浏览器--解决办法
开发语言·javascript·ecmascript
Jedi Hongbin3 小时前
Three.js NodeMaterial 节点材质系统文档
前端·javascript·three.js·nodematerial
前端小马3 小时前
前后端Long类型ID精度丢失问题
java·前端·javascript·后端
liu****4 小时前
基于websocket的多用户网页五子棋(八)
服务器·前端·javascript·数据库·c++·websocket·个人开发
San304 小时前
深入理解 JavaScript 函数:从基础到高阶应用
前端·javascript·node.js
芒果茶叶5 小时前
并行SSR,SSR并行加载
前端·javascript·架构
威风的虫6 小时前
JavaScript中的axios
开发语言·javascript·ecmascript