Skip to content

移除选择器

可用于移除三方库中的不需要的样式,从而减小包体积。

1. 作者

novlan1

2. 如何使用

安装

bash
pnpm add @novlan/postcss-plugin-remove-selector -D

简化模式(推荐)

通过 mode 指定预设,只需关注 used/unused,无需手动配置 fileselectorPattern

ts
import { defineConfig } from 'vite';
import { postcssPluginRemoveSelector } from '@novlan/postcss-plugin-remove-selector';

export default defineConfig({
  css: {
    postcss: {
      plugins: [
        postcssPluginRemoveSelector({
          mode: 'tdesign',
          used: ['home', 'chat', 'user', 'add', 'search', 'close'],
        }),
      ],
    },
  },
});

使用 customUsed / customUnused 可在预设基础上增量追加,不会覆盖预设中已有的列表:

ts
postcssPluginRemoveSelector({
  mode: 'tdesign',
  // 在 tdesign 预设默认的 used 列表上,额外追加 'star' 和 'heart'
  customUsed: ['star', 'heart'],
  // 从结果中额外移除 'loading'
  customUnused: ['loading'],
})

标准模式

通过 list 数组传入完整配置,适用于需要匹配多个文件的复杂场景:

ts
import { defineConfig } from 'vite';
import { postcssPluginRemoveSelector } from '@novlan/postcss-plugin-remove-selector';
import {
  TDESIGN_ICON_REMOVE_SELECTOR
} from '@novlan/postcss-plugin-remove-selector/lib/tdesign-uniapp-icon';


export default defineConfig({
  css: {
    postcss: {
      plugins: [postcssPluginRemoveSelector(TDESIGN_ICON_REMOVE_SELECTOR)],
    },
  },
});

3. 类型

插件支持两种配置方式,传入 SimpleOptions(简化模式)或 Options(标准模式)均可。

SimpleOptions(简化模式)

属性类型是否必填说明
mode'tdesign'预设模式,设置后自动使用对应的 fileselectorPattern 默认值
fileRegExp | string文件匹配规则。使用 mode 时可省略
usedstring[]正在使用的图标名称列表,这些图标会被保留
unusedstring[]未使用的图标名称列表,这些图标会被移除
customUsedstring[]增量追加到 used 列表(不覆盖预设或已有的 used
customUnusedstring[]增量追加到 unused 列表(不覆盖预设或已有的 unused
selectorPatternRegExp选择器匹配模式。使用 mode 时可省略
debugboolean是否开启调试模式

modefile 至少需要指定一个。当 modefile/selectorPattern 同时指定时,file/selectorPattern 优先。

Options(标准模式)

属性类型是否必填说明
listFileConfig[]配置列表
debugboolean是否开启调试模式

FileConfig

属性类型是否必填说明
fileRegExp | string文件匹配规则,可以是字符串或正则表达式
usedstring[]正在使用的图标名称列表,这些图标会被保留
unusedstring[]未使用的图标名称列表,这些图标会被移除
customUsedstring[]增量追加到 used 列表(不覆盖已有的 used
customUnusedstring[]增量追加到 unused 列表(不覆盖已有的 unused
selectorPatternRegExp选择器匹配模式,只处理匹配该模式的选择器

内置预设

mode说明默认 file默认 selectorPattern
tdesignTDesign UniApp 图标减包/[@/]tdesign[/]uniapp[/]dist[/]icon[/]icon\.[css|vue]//^\.t-icon-[\w-]+:before$/

4. 更新日志

点此查看

5. 效果

tdesign-uniapp-starter 为例,使用此插件,可使小程序大小减少138KB,约95.8%

使用前:

使用后: