Reputation: 1687
My app displays social media links and specifies the icon to display with each link.
I'm using the oh-vue-icons icon library. If you import the whole thing, it's huge. So I want to import only the icons I have defined links for. However, when I try to do the dynamic imports, it breaks tree shaking and I'm left with the entire library.
Here's my /src/data/social-links.js
where I define the links and their icon name:
export default [
{
name: "LinkedIn",
url: "...",
iconName: "CoLinkedinIn"
},
{
name: "GitHub",
url: "...",
iconName: "CoGithub"
}
]
Now in my Vue code, SocialLinks.vue
, I have:
import socialLinks from "/src/data/social-links.js"
import { ref, onBeforeMount } from "vue"
import { addIcons } from "oh-vue-icons"
const iconsLoaded = ref(false)
onBeforeMount(() => {
importIcons()
})
const importIcons = async () => {
const iconNames = socialLinks.map(link => link.iconName)
await import("oh-vue-icons/icons").then(module => {
const iconModules = iconNames.map(name => module[name])
addIcons(...iconModules)
iconsLoaded.value = true
})
}
I have also tried an alternative approach in importIcons
. But it didn't work either:
const importIcons = async () => {
Promise.all(
socialLinks.map(async (link) => {
const { [link.iconName]: iconModule } = await import("oh-vue-icons/icons")
return iconModule
})
).then((modules) => {
addIcons(...modules)
iconsLoaded.value = true
})
}
This works on the front-end code, however, tree shaking doesn't work.
I imagine this has something to do with not being able to evaluate the runtime code. But perhaps there's something I can do as a pre-build step?
I'm using Vue and Vite
"vue": "^3.4.29"
"vite": "^5.3.1"
Upvotes: 0
Views: 354
Reputation: 166
I think the tree shaking still get some bugs in Vite(5.x), instead of replying on dynamic import, change to only import the icons you need might be a better way.
import { CoLinkedinIn, CoGithub } from "oh-vue-icons/icons"
export default [
{
name: "LinkedIn",
url: "...",
iconName: CoLinkedinIn
},
{
name: "GitHub",
url: "...",
iconName: CoGithub
}
]
The reason you choose the dynamic imports is to reduce the size of oh-vue-icons
. The static import approach above actually achieves the same effect.
By using static import, Vite could effectively perform the tree shaking, including the only those icons in your final bundle, and exclude the no-used parts of library.
Upvotes: 1