Another mechanism that the SVG Core provides is a JavaScript class called Library.
With a subsetted Kit, this can be an easy way to add all icons once and use them with a syntax that requires less typing.
Now all icons in the Kit have been added in just one, easy line. No fuss, no muss.
Using it doesn’t require importing the icons. You just need an array or string.
Also note here that we’ve switched from importing and using FontAwesomeIcon
directly and are using the already registered component, through
app.component(). That means our syntax shifts slightly and we use
<font-awesome-icon ...> now.
If you can’t or don’t want to use a Kit, you can explicitly add individual icons to each component. Here’s a simple example:
Add Individual Icons Explicitly
Notice that the faEnvelope icon is imported from @fortawesome/free-solid-svg-icons as an object and then provided to the icon prop as an object.
Add Icons Globally
We like to travel light so we don’t recommend this method unless you know what you’re doing. Globally importing icons can increase the size of your bundle with icons you aren’t using. It also couples your components to another module that manages your icons.
First, you’ll import the icons you want to use via a “library” in the initializing module of your React application, like App.js. Here’s an example of that:
In our call to library.add() we’re passing:
fas: which represents all of the icons in @fortawesome/free-solid-svg-icons. (Be careful importing whole styles - it can be a LOT of icons!) So any of the icons in that package may be referenced by icon name as a string anywhere else in our app. For example: coffee, check-square, or spinner.
faTwitter, faFontAwesome, faHatCowboy, faHatChef, and faPlateUtensils: Adding each of these icons individually allows us to refer to them throughout our app by their icon string names, twitter, font-awesome, hat-cowboy, hat-chef, and plate-utensils.
You can then use any of those icons anywhere in your app without needing to re-import into each component. So if you used icons in a couple of components, that would end up looking something like this:
You’ll notice we were able use the imported brand icons without explicitly importing them in the component. And we used the square-check, and envelope icons without explicitly importing them anywhere. But, our bundle now has over 1000 solid icons plus the two brand icons we added, which is more than we’re using - a good reason to avoid importing a whole style.
Same icons, Different Styles
Using ES modules and import statements we can define unique names for two different styles of the same icon. Here’s an example:
If you are using inline templates or HTML as templates you need to be careful to avoid self-closing tags. Read more about self-closing tags on Vue.js. If you are writing these types of templates, you’ll need to adjust the syntax to be valid HTML, like this: