In Ionic Angular standalone setups, how you handle ion-icon changed. Specifically:
Previously:
- Copy SVG files from
node_modules/ionicons/dist/ionicons/svginto the project - Load the SVG file matching
ion-icon[name] - Display
Standalone setup:
- Before display, load SVG data with
addIconsand register it on the window - Read SVG data from the window for
ion-icon[name] - Display
This shrinks bundle size, but unlike copying every SVG up front, you must manually addIcons beforehand, which adds work. Forgetting addIcons fails at display time, not build time, which makes errors harder to trace. Even with visual checks, you can hit cases like this:
Suppose you use
CloseOutline(name=close-outline) on both page A and page B, and page A always loads before page B.
Page A → navigate → Page B
If you only calladdIcons(CloseOutline)on page B, the icon does not show on page A but does on page B. If you only call it on page A, it shows on both pages.
To solve this, I built ionic-angular-collect-icons, a library that automatically collects ion-icon name values and runs addIcons.
ionic-angular-collect-icons
What it does
This library automatically collects ion-icon usage in the project, groups icons uniquely, and generates a file for ion-icon exports.
During development: add every icon with addIcons for stress-free development.
In production: before each build, collect and update icons used in templates automatically.
Of course, to maximize bundle savings you should load the minimum icons when each component lazy-loads. This is a compromise to speed up development.
Usage
Initial setup
The following command performs all initial setup automatically.
% npm install @rdlabo/ionic-angular-collect-icons --save-dev
What initial setup does
- Creates
src/use-icons.ts - Adds the following to
main.ts(orapp.config.ts):
+ import { addIcons } from 'ionicons';
+ import * as allIcons from 'ionicons/icons';
+ import * as useIcons from '../use-icons';
if (environment.production) {
enableProdMode();
}
+ addIcons(environment.production ? useIcons : allIcons);
- Removes
addIconsfrom every component
@Component(/* ... */)
export class ExampleComponent {
constructor() {
- addIcons(useIcons);
}
}
Run before build
Before building, run the following to collect icons and update src/use-icons.ts each time.
% npx @rdlabo/ionic-angular-collect-icons
Running the command manually before every build is unrealistic, so I recommend adding it to the npm prebuild script.
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
+ "prebuild": "npx @rdlabo/ionic-angular-collect-icons"
Options are available for multiple workspaces and custom output paths. See:
https://github.com/rdlabo-dev/ionic-angular-collect-icons?tab=readme-ov-file#optional