Jevon617 / unplugin-svg-component

generate a vue/react component through svg files, supporting svg file HMR, Tree-shaking, SSR and TS hint.
MIT License
58 stars 5 forks source link

React/Vite - Tree-shaking not working, all svg in iconDir are included, even if none used #24

Closed TeChn4K closed 4 months ago

TeChn4K commented 4 months ago

Hi,

Tree shaking is not working for me. All SVGs in the iconDir directory are included, even if none are actually used in the codebase.

vite.config.js

defineConfig({
  plugins: [
    react(),
    unpluginSvgComponent({
      iconDir: path.resolve(__dirname,'./path/to/svgs'),
      dts: true,
      dtsDir: path.resolve(__dirname, './src/types'),
      projectType: 'react',
      treeShaking: true,
    }),
...

Then I don't use import SvgIcon from '~virtual/svg-component' at all, but all SVGs are included in the sprite

Am i missing something?


Edit for futur readers: tree-shaking is only enabled at build time, not in dev mode.

Jevon617 commented 4 months ago

@TeChn4K Maybe you can set scanStrategy to 'text'

TeChn4K commented 4 months ago

Unfortunately the scanStrategy: 'text' option didn't help

I made a demo codesandbox for you here

You can see that the svgs folder contains two files : alarm & album Only the alarm icon is used in App.tsx But the sprite contains the two icons

Jevon617 commented 4 months ago

image

Tree shaking only works on the build mode, and it works correctly. In my understanding, tree shaking in dev mode is meaningless.

TeChn4K commented 4 months ago

Sorry, I thought it was also done in dev mode, thanks for the clarification.

In my use case, it is not so meaningless. Ideally, I would like to point iconDir to node_modules/@material-symbols/svg which contains several thousand icons. My laptop is literally burning with all these icons in the DOM.

Do you think it can be doable to enable tree-shaking in dev mode?

Jevon617 commented 4 months ago

The tree shaking uses regex to match the icon name, so it is slow, it is impossible to enable it in dev mode.

I think unplugin-icons is better suited for your use case, which imports icons for

demand.

TeChn4K commented 4 months ago

Too bad! Because unplugin-icons is a good tool but it does not handle svg sprite. Thanks for your time.