unplugin / unplugin-icons

🤹 Access thousands of icons as components on-demand universally.
https://www.npmjs.com/package/unplugin-icons
MIT License
3.66k stars 131 forks source link

Add support for named exports #261

Open mammadataei opened 1 year ago

mammadataei commented 1 year ago

Clear and concise description of the problem

With default exports, editors/IDEs can not suggest auto-import for icons.

<IconAccountBox />
// ^? TS2304: Cannot find name 'IconAccountBox'.

So you need to import the icon manually.

import IconAccountBox from '~icons/mdi/account-box'

Suggested solution

If the plugin supports generating named exports, it is possible to generate type declarations for all icons in the desired icon set with a tiny script:

// this one gets an auto-import suggestion
import { IconAccountBox } from '~icons/mdi/account-box'
// generate a .d.ts file for exports
import { icons } from '@iconify-json/mdi'

const exports = Object.keys(icons).map(
    (icon) => 
      `declare module 'virtual:icons/mdi/${icon}' {
        import type { SVGProps, ReactElement } from 'react'

        const component: (props: SVGProps<SVGSVGElement>) => ReactElement
        export { component as Icon${icon} }
      }`,
).join('\n')

fs.writeFileSync('...', exports

I think it is even possible to let the user define the naming convention for exports:

export default defineConfig({
  plugins: [
    Icons({
      exports: {
        named: true,
        convention: (icon) => `Icon${icon}`,
      },
    }),
  ],
})

Alternative

No response

Additional context

No response

Validations