### Install @purge-icons/core Source: https://github.com/antfu/purge-icons/blob/main/README.md Install the core package for programmatic use. ```bash npm i -D @purge-icons/core ``` -------------------------------- ### Example: fetchCollection('mdi', 'local') Source: https://github.com/antfu/purge-icons Shows how to import and call fetchCollection with a local source. The example fetches the 'mdi' collection locally and returns a Promise. ```ts import { fetchCollection } from '@purge-icons/core' // internal module export const mdi = await fetchCollection('mdi', 'local') ``` -------------------------------- ### Install nuxt-purge-icons-module and @iconify/iconify Source: https://github.com/antfu/purge-icons/blob/main/packages/nuxt-purge-icons-module/README.md Install the Nuxt module and the required Iconify runtime dependency using npm. ```sh npm i nuxt-purge-icons-module -D npm i @iconify/iconify@2 ``` -------------------------------- ### Options from nuxt.config Source: https://github.com/antfu/purge-icons Configuration example showing how to set content, included, and iconSource options via the purgeIcons key in nuxt.config.js. ```javascript // nuxt.config.js export default { buildModules: ['nuxt-purge-icons-module'], purgeIcons: { content: ['**/*.html', '**/*.vue'], included: ['carbon:moon', 'carbon:sun'], iconSource: 'local', }, } ``` -------------------------------- ### Iconify icon usage examples Source: https://github.com/antfu/purge-icons/blob/main/README.md Shows how to use icons from different Iconify collections with the iconify class and data-icon attribute. ```html ``` -------------------------------- ### Install PurgeIcons globally Source: https://github.com/antfu/purge-icons/blob/main/README.md Install PurgeIcons as a global package to use the CLI directly. Alternatively, install it as a dev dependency and use npx. ```bash npm i -g purge-icons ``` -------------------------------- ### Install purge-icons-webpack-plugin Source: https://github.com/antfu/purge-icons/blob/main/packages/purge-icons-webpack-plugin/README.md Install the plugin as a dev dependency using npm or yarn. ```bash npm i purge-icons-webpack-plugin -D # yarn add purge-icons-webpack-plugin -D ``` -------------------------------- ### Options as module options Source: https://github.com/antfu/purge-icons Configuration example showing how to pass options directly to the build module as an array with the module name and options object. ```javascript // nuxt.config.js export default { buildModules: [ ['nuxt-purge-icons-module', { format: 'mjs' }], ], } ``` -------------------------------- ### Install rollup-plugin-purge-icons Source: https://github.com/antfu/purge-icons/blob/main/packages/rollup-plugin-purge-icons/README.md Install the plugin as a dev dependency using npm or yarn. ```bash npm i rollup-plugin-purge-icons -D # yarn add rollup-plugin-purge-icons -D ``` -------------------------------- ### Install vite-plugin-purge-icons and dependencies Source: https://github.com/antfu/purge-icons/blob/main/packages/vite-plugin-purge-icons/README.md Install the required packages. @iconify/json is optional; if present in node_modules, PurgeIcons loads icons locally, otherwise it fetches iconsets online. Vite 2 is supported from v0.5.x; Vite 1 support is discontinued. ```bash npm i @iconify/iconify npm i vite-plugin-purge-icons @iconify/json -D ``` -------------------------------- ### Programmatic usage with @purge-icons/core Source: https://github.com/antfu/purge-icons Options passed to PurgeIcons({ ... }) for programmatic use. The example shows importing PurgeIcons and calling it with content, included, and format options. ```ts import { PurgeIcons } from '@purge-icons/core' const code = await PurgeIcons({ content: ['**/*.html', '**/*.vue'], included: ['mdi:account-circle-outline', 'fa:camera'], format: 'mjs', }) ``` -------------------------------- ### CLI usage with purge-icons Source: https://github.com/antfu/purge-icons Example of using the purge-icons CLI with flags -c and -o. The CLI maps flags to PurgeIconsOptions; --content is required, --output writes to a file. ```bash purge-icons -c 'index.html,src/**/*.vue' -o output.ts ``` -------------------------------- ### Example — default ESM module Source: https://github.com/antfu/purge-icons Generates an ESM module string for the 'mdi:home' icon using the default format 'mjs'. ```ts import { CodeGen } from '@purge-icons/core' const code = await CodeGen(['mdi:home'], { format: 'mjs' }) // Generated: imports 'mdi' collection, adds it to Iconify, exports Iconify ``` -------------------------------- ### Example — custom iconify import + JSON Source: https://github.com/antfu/purge-icons Generates JSON output and a CommonJS module with a custom iconify import name. ```ts import { CodeGen } from '@purge-icons/core' const json = await CodeGen(['mdi:home'], { format: 'json' }) const cjs = await CodeGen(['mdi:home'], { format: 'cjs', iconifyImportName: 'my-iconify-wrapper', }) ``` -------------------------------- ### Basic usage in vite.config.js Source: https://github.com/antfu/purge-icons Minimal setup: import PurgeIcons and add it to the plugins array. No options needed; defaults apply. ```TypeScript // vite.config.js import PurgeIcons from 'vite-plugin-purge-icons' export default { plugins: [ PurgeIcons(), ], } ``` -------------------------------- ### Extract() usage example Source: https://github.com/antfu/purge-icons Shows how to call Extract with content globs and raw content, returning a de-duplicated array of raw icon keys like 'mdi:home'. Keys are not validated against known collections. ```ts import { Extract } from '@purge-icons/core' const names = await Extract({ content: [ 'src/**/*.js', { extension: '.html', raw: '' }, ], }) // ['mdi:home', ...] ``` -------------------------------- ### Import @purge-icons/generated in main.js Source: https://github.com/antfu/purge-icons/blob/main/packages/vite-plugin-purge-icons/README.md Import the generated icons module in your entry file (e.g., main.js) to enable the plugin's generated icons. This example shows it in a Vue app setup. ```ts import { createApp } from 'vue' import App from './App.vue' import '@purge-icons/generated' // <-- This createApp(App).mount('#app') ``` -------------------------------- ### Usage example: next.config.js with next-purge-icons (no-op) Source: https://github.com/antfu/purge-icons Shows how to wire the stub plugin into a Next.js config. Currently has no effect because the default export is a no-op. ```JavaScript // next.config.js — currently has no effect const withPurgeIcons = require('next-purge-icons') module.exports = withPurgeIcons({}) ``` -------------------------------- ### Basic usage of PurgeIcons Source: https://github.com/antfu/purge-icons Example showing how to call `PurgeIcons` with content globs and included icons, then write the generated module to a file. Uses `format: 'mjs'` (the default). ```TypeScript import { PurgeIcons } from '@purge-icons/core' import fs from 'fs/promises' const code = await PurgeIcons({ content: ['**/*.html', '**/*.vue'], included: ['mdi:account-circle-outline', 'fa:camera'], format: 'mjs', }) await fs.writeFile('./icons.mjs', code, 'utf-8') ``` -------------------------------- ### Basic usage in webpack.config.js Source: https://github.com/antfu/purge-icons Example webpack configuration that adds the PurgeIcons plugin with a content glob pattern. ```ts // webpack.config.js const PurgeIcons = require('purge-icons-webpack-plugin') module.exports = { plugins: [ new PurgeIcons({ content: ['src/**/*.{html,js,vue}'], }), ], } ``` -------------------------------- ### GetIconsData() usage example Source: https://github.com/antfu/purge-icons Imports GetIconsData from '@purge-icons/core' and fetches icon data with local source. Logs the prefix and icon data. ```ts import { GetIconsData } from '@purge-icons/core' const data = await GetIconsData(['mdi:home'], { iconSource: 'local' }) console.log(data[0].prefix) // 'mdi' console.log(data[0].icons['home']) ``` -------------------------------- ### Extract with DefaultExtractor Source: https://github.com/antfu/purge-icons Example of using the Extract function with the DefaultExtractor. The defaultExtractor option is explicitly set, though it is already the default. ```typescript import { Extract, DefaultExtractor } from '@purge-icons/core' const names = await Extract({ content: ['index.html'], defaultExtractor: DefaultExtractor, // explicit, though it's already the default }) ``` -------------------------------- ### ParseIconNames() usage example Source: https://github.com/antfu/purge-icons Imports ParseIconNames from '@purge-icons/core' and parses an array of icon keys. The result groups icon names by collection. ```ts import { ParseIconNames } from '@purge-icons/core' const parsed = ParseIconNames(['mdi:home', 'mdi:alert', 'fa:camera']) // { mdi: ['home', 'alert'], fa: ['camera'] } ``` -------------------------------- ### Usage example: vue-cli-plugin-purge-icons (no-op) Source: https://github.com/antfu/purge-icons Shows the equivalent no-op for parcel, gridsome, and vue-cli plugins. Calling the plugin returns undefined and has no effect. ```JavaScript // parcel / gridsome / vue-cli equivalents similarly no-op const plugin = require('vue-cli-plugin-purge-icons') plugin() // returns undefined, no-op ``` -------------------------------- ### Programmatic use of purge-icons as a library Source: https://github.com/antfu/purge-icons The package can be used as a library with the same API as @purge-icons/core. This example imports PurgeIcons and generates code with format 'cjs'. ```ts import { PurgeIcons } from 'purge-icons' const code = await PurgeIcons({ content: ['**/*.html'], format: 'cjs' }) console.log(code) ``` -------------------------------- ### Usage with included icons in webpack.config.js Source: https://github.com/antfu/purge-icons Example webpack configuration that specifies included icons and a local icon source. ```ts // webpack.config.js const PurgeIcons = require('purge-icons-webpack-plugin') module.exports = { plugins: [ new PurgeIcons({ content: ['index.html'], included: ['carbon:moon', 'carbon:sun'], iconSource: 'local', }), ], } ``` -------------------------------- ### Error handling with JSON output Source: https://github.com/antfu/purge-icons Example showing how to catch errors from `PurgeIcons` when using `format: 'json'`. The `included` array contains an invalid collection prefix, which will cause the promise to reject. ```TypeScript import { PurgeIcons } from '@purge-icons/core' try { const json = await PurgeIcons({ content: ['index.html'], included: ['not-a-real-collection:home'], // invalid collection prefix format: 'json', }) console.log(json) } catch (err) { console.error('PurgeIcons failed:', err) } ``` -------------------------------- ### VerifyCollection usage Source: https://github.com/antfu/purge-icons Example of using VerifyCollection to check if a collection id is known. Logs 'mdi is a known collection' if the check passes, otherwise logs 'unknown collection'. ```typescript import { VerifyCollection } from '@purge-icons/core' if (VerifyCollection('mdi')) console.log('mdi is a known collection') else console.log('unknown collection') ``` -------------------------------- ### Catch Unknown output format error Source: https://github.com/antfu/purge-icons Example of catching the Unknown output format error from CodeGen. Uses a regex test on the error message to identify the failure and logs the allowed formats. ```ts import { CodeGen } from '@purge-icons/core' try { await CodeGen(['mdi:home'], { format: 'invalid' }) } catch (err) { if (err instanceof Error && /Unknown output format/.test(err.message)) console.error(`Formats allowed: js, mjs, cjs, ts, json — got ${(err.message.match(/"(.+)"/) || [])[1]}`) } ``` -------------------------------- ### IconSource type Source: https://github.com/antfu/purge-icons Defines the collection source strategy for fetchCollection: 'local' reads installed packages, 'remote' queries the API, 'auto' tries local then falls back to remote. ```ts export type IconSource = 'local' | 'remote' | 'auto' ``` -------------------------------- ### Catch Invalid collection name error Source: https://github.com/antfu/purge-icons Example of catching the Invalid collection name error from PurgeIcons. Uses a regex test on the error message to identify the failure and logs a removal instruction. ```ts import { PurgeIcons } from '@purge-icons/core' try { await PurgeIcons({ content: [/* ... */], included: ['bogus:home'] }) } catch (err) { if (err instanceof Error && /Invalid collection name/.test(err.message)) console.error('Remove the bad collection from `included`.') else throw err } ``` -------------------------------- ### CollectionId type and generated code Source: https://github.com/antfu/purge-icons Discriminated string union of every collection id known to Iconify. This file is generated at build time by packages/@purge-icons/core/scripts/prepare.ts, which reads @iconify/json/collections.json and emits the shown code. Not present in committed source tree; actual list depends on installed @iconify/json. ```ts // generated — src/generated/collections.ts (see below) export type CollectionId = '1f' | 'a' | 'academicons' | 'adobe' | ... // union of every known collection id ``` ```ts export type CollectionId = ${Object.keys(collections).map(i => `'${i}'`).join(' | ')} export const CollectionIds: Array = [/* every id */] export const ExtractorRegex = /(?:${Object.keys(collections).join('|')}):[\w\d-]+/g ``` -------------------------------- ### Show CLI help Source: https://github.com/antfu/purge-icons/blob/main/README.md Displays all available CLI options and usage information. ```bash purge-icons --help ``` -------------------------------- ### Output to stdout and show help Source: https://github.com/antfu/purge-icons Without --output, the generated code is printed to stdout. The --help flag displays the CLI help text. ```bash purge-icons --content index.html purge-icons --help ``` -------------------------------- ### Scan HTML files and generate mjs bundle Source: https://github.com/antfu/purge-icons/blob/main/README.md Scans all HTML files matching the content glob and generates an mjs bundle at the specified output path. ```bash purge-icons --content 'src/*.html' --format mjs --output output.js ``` -------------------------------- ### Default options for nuxt-purge-icons-module Source: https://github.com/antfu/purge-icons Default options object for nuxt module. Merge precedence: defaultOptions < this.options.purgeIcons < moduleOptions. ```js const defaultOptions = { content: ['**/*.html', '**/*.vue', '**/*.js', '**/*.ts'], } ``` -------------------------------- ### Export plain JSON for other tools Source: https://github.com/antfu/purge-icons Outputs the generated code as JSON, inferred from the .json extension. Useful for interoperability with other tools. ```bash purge-icons -c index.html -o output.json ``` -------------------------------- ### Scan multiple sources with shorthand flags Source: https://github.com/antfu/purge-icons/blob/main/README.md Uses shorthand flags -c and -o to scan multiple sources. The format is auto-inferred from the output file extension. ```bash purge-icons -c 'index.html,src/**/*.vue' -o output.ts ``` -------------------------------- ### Binary entry for purge-icons CLI Source: https://github.com/antfu/purge-icons The binary entry simply requires the compiled CLI. It is the entry point for the purge-icons command. ```js #!/usr/bin/env node 'use strict' require('../dist/cli') ``` -------------------------------- ### Scan HTML files and emit an ESM bundle Source: https://github.com/antfu/purge-icons Scans source files matching the glob and outputs an ESM bundle to the specified file. The --format flag is explicitly set to mjs. ```bash purge-icons --content 'src/*.html' --format mjs --output output.js ``` -------------------------------- ### new PurgeIcons(options) Source: https://github.com/antfu/purge-icons Creates a new PurgeIcons webpack plugin instance. The constructor accepts optional PurgeIcons options and initializes an internal virtual module plugin. ```APIDOC ## Constructor: new PurgeIcons(options) ### Description Creates a new PurgeIcons webpack plugin instance. The constructor accepts optional PurgeIcons options and initializes an internal virtual module plugin. ### Parameters - **options** (`PurgeIconsOptions`) - Optional, default `{}` - PurgeIcons options. `format` is hard-coded to `'cjs'` internally. ### Example ```ts // webpack.config.js const PurgeIcons = require('purge-icons-webpack-plugin') module.exports = { plugins: [ new PurgeIcons({ content: ['src/**/*.{html,js,vue}'], }), ], } ``` ```ts // webpack.config.js const PurgeIcons = require('purge-icons-webpack-plugin') module.exports = { plugins: [ new PurgeIcons({ content: ['index.html'], included: ['carbon:moon', 'carbon:sun'], iconSource: 'local', }), ], } ``` ``` -------------------------------- ### Default options for vite-plugin-purge-icons Source: https://github.com/antfu/purge-icons Default options object merged under user options (user wins) for createPlugin. Includes content patterns and iconifyImportName. ```ts { content: ['**/*.html', '**/*.pug', '**/*.vue', '**/*.js', '**/*.ts'], iconifyImportName: '@iconify/iconify', ...options, } ``` -------------------------------- ### Basic usage in rollup.config.js Source: https://github.com/antfu/purge-icons Minimal Rollup configuration using the plugin with content globs and format 'mjs'. No default content is supplied, so options are required. ```ts // rollup.config.js import PurgeIcons from 'rollup-plugin-purge-icons' export default { input: 'src/main.js', plugins: [ PurgeIcons({ content: ['src/**/*.{html,js}'], format: 'mjs', }), ], } ``` -------------------------------- ### apply(compiler) Source: https://github.com/antfu/purge-icons Applies the plugin to the webpack compiler. It applies the internal virtual module plugin, runs the Purge pipeline, and writes the generated code to the virtual module. ```APIDOC ## Method: apply(compiler) ### Description Applies the plugin to the webpack compiler. It applies the internal virtual module plugin, runs the Purge pipeline, and writes the generated code to the virtual module. ### Parameters - **compiler** (`Compiler`) - Required - The webpack compiler instance. ### Returns `void` ### Behavior 1. Applies the inner `VirtualModulesPlugin` to the compiler. 2. Runs `Purge({ ...this.options, format: 'cjs' })`. 3. On resolution, writes the generated code into the virtual module at `node_modules/@purge-icons/generated`. ### Errors Rejects on any core pipeline error (invalid collection, fetch failure, unknown format). ### Example ```ts // webpack.config.js const PurgeIcons = require('purge-icons-webpack-plugin') module.exports = { plugins: [ new PurgeIcons({ content: ['src/**/*.{html,js,vue}'], }), ], } ``` Then your app entry imports the generated module: ```js import '@purge-icons/generated' ``` ``` -------------------------------- ### PurgeIcons() Source: https://github.com/antfu/purge-icons Primary entry point that runs the full pipeline: extract icon names from content, fetch icon collections, and generate a bundle containing only the used icons. Returns a Promise resolving to a generated module source string or JSON string depending on the format option. ```APIDOC ## PurgeIcons() ### Description Primary entry point that runs the full pipeline: extract icon names from content, fetch icon collections, and generate a bundle containing only the used icons. Returns a Promise resolving to a generated module source string or JSON string depending on the format option. ### Method async function ### Signature ```ts export async function PurgeIcons(options: PurgeIconsOptions = {}) ``` ### Parameters - **options** (`PurgeIconsOptions`) - Optional, default `{}` - Options object (see configuration) ### Returns `Promise` — a generated module source string. The format depends on `options.format` (default `mjs`): a JavaScript/CJS/TS module that imports `@iconify/iconify`, registers each bundled collection, and exports the Iconify instance. When `format === 'json'`, returns a raw JSON string of the collection data array. ### Rejects - Any error thrown by `Extract` or `CodeGen` (e.g. invalid collection name, failed collection fetch, unknown output format). See errors. ### Request Example ```ts import { PurgeIcons } from '@purge-icons/core' import fs from 'fs/promises' const code = await PurgeIcons({ content: ['**/*.html', '**/*.vue'], included: ['mdi:account-circle-outline', 'fa:camera'], format: 'mjs', }) await fs.writeFile('./icons.mjs', code, 'utf-8') ``` ### Request Example (error handling) ```ts import { PurgeIcons } from '@purge-icons/core' try { const json = await PurgeIcons({ content: ['index.html'], included: ['not-a-real-collection:home'], // invalid collection prefix format: 'json', }) console.log(json) } catch (err) { console.error('PurgeIcons failed:', err) } ``` ``` -------------------------------- ### CodeGen(icons, options) Source: https://github.com/antfu/purge-icons Given a list of icon keys, fetches their data and produces the output module (or JSON) string. This is the primary function for generating bundled icon data in various formats. ```APIDOC ## CodeGen(icons, options) ### Description Given a list of icon keys, fetches their data and produces the output module (or JSON) string. This is the primary function for generating bundled icon data in various formats. ### Method CodeGen ### Endpoint CodeGen(icons: string[], options: PurgeIconsOptions = {}) ### Parameters #### Function Parameters - **icons** (`string[]`) - Required - Icon keys to bundle, including any `options.included` already merged by `PurgeIcons`. - **options** (`PurgeIconsOptions`) - Optional - Uses `format`, `iconifyImportName`. ### Returns `Promise`: - If `format === 'json'` — returns `JSON.stringify(data)` where `data` is the `IconifyJSON[]` array. - Otherwise returns a module source. `format` dispatch: - `'js'` | `'cjs'`: `const Iconify = require('').default` / `module.exports = Iconify` - `'mjs'` | `'ts'` | `undefined` (default): `import Module from ''\nconst Iconify = Module.default || Module` / `export default Iconify` - anything else: `throw new Error(\`Unknown output format "${options.format}"\`)` - The collection data is JSON-inlined into the module (escaped for backslashes and single quotes). - `` defaults to `@iconify/iconify`, overridable via `options.iconifyImportName`. - The generated module iterates the collections and calls `Iconify.addCollection(c)` for each. ### Throws `Error` — message `` `Unknown output format "${options.format}"` `` for any format not in the dispatch list (which means `'json'` is excluded from this branch because it returns earlier). ### Request Example ```ts import { CodeGen } from '@purge-icons/core' const code = await CodeGen(['mdi:home'], { format: 'mjs' }) // Generated: imports 'mdi' collection, adds it to Iconify, exports Iconify ``` ```ts import { CodeGen } from '@purge-icons/core' const json = await CodeGen(['mdi:home'], { format: 'json' }) const cjs = await CodeGen(['mdi:home'], { format: 'cjs', iconifyImportName: 'my-iconify-wrapper', }) ``` ``` -------------------------------- ### Direct use Source: https://github.com/antfu/purge-icons Direct usage of the package's default export, which is the @iconify/iconify instance. The full @iconify/iconify API surface applies. ```javascript import Iconify from '@purge-icons/generated' Iconify.addIcon('custom', { body: '', width: 24, height: 24 }) ``` -------------------------------- ### PurgeIcons apply method signature Source: https://github.com/antfu/purge-icons Applies the plugin to the webpack compiler. Returns void. ```ts apply(compiler: Compiler) ``` -------------------------------- ### Default options for content Source: https://github.com/antfu/purge-icons Default content patterns used when no options are provided. These are merged with user options. ```javascript const defaultOptions = { content: [ '**/*.html', '**/*.vue', '**/*.js', '**/*.ts', ], } ``` -------------------------------- ### fetchCollection() function signature Source: https://github.com/antfu/purge-icons Defines the fetchCollection function that resolves an Iconify collection from local packages or a remote API, caches the result, and resolves aliases. Parameters include name, source, remoteDataAPI, and cache with defaults. Returns a Promise. ```ts export async function fetchCollection( name: CollectionId, source: IconSource = 'auto', remoteDataAPI = DEFAULT_API_PATH, cache: CollectionCache = default_cache, ): Promise ``` -------------------------------- ### Export plain JSON file Source: https://github.com/antfu/purge-icons/blob/main/README.md Exports the scan results as a plain JSON file for processing by other tools. ```bash purge-icons -c index.html -o output.json ``` -------------------------------- ### Configure nuxt-purge-icons-module in nuxt.config.js Source: https://github.com/antfu/purge-icons/blob/main/packages/nuxt-purge-icons-module/README.md Add the module to buildModules and set the purgeIcons options in nuxt.config.js. ```js module.exports = { /* ...config */ buildModules: [ 'nuxt-purge-icons-module' ], purgeIcons: { /* PurgeIcons Options */ } } ``` -------------------------------- ### purge-icons CLI Source: https://github.com/antfu/purge-icons The `purge-icons` command scans source files, bundles used icons, and writes (or prints) the generated module. It accepts options for output path, content globs, included icons, and output format. ```APIDOC ## [CLI] purge-icons ### Description Scans source files, bundles used icons, and writes (or prints) the generated module. The command is defined with yargs and uses a single catch-all implicit command ('*'). ### Usage ```bash purge-icons [args] ``` ### Options | Option | Alias | Type | Required | Default | Description | |--------|-------|------|----------|---------|-------------| | `--output` | `-o` | `string` | no | — | Path for the output file. When omitted, the generated code is printed to stdout. | | `--content` | `-c` | `string, array` | yes | — | Glob(s) for matching source files, comma-separated. Each value is split on commas, trimmed, and empty entries removed. | | `--included` | `-i` | `string, array` | yes/no* | — | Whitelist of icons to always bundle (for dynamically-used icons). *Not marked required; but passed through even when `undefined`. | | `--format` | `-f` | `string` | no | inferred (else `mjs`) | Output format. `choices: ['js', 'mjs', 'cjs', 'ts', 'json']`. | **Format inference:** the resolved `format` is `args.format || path.parse(args.output)?.ext?.slice(1)?.toLowerCase() || 'mjs'`. In practice this means the format is auto-inferred from the output file extension when `--format` is not given (e.g. `-o output.ts` → `ts`, `-o output.json` → `json`), falling back to `mjs`. `--content` is a comma-separated array; the handler flattens each provided value with `.flatMap(i => i.split(','))`. ### Exit / output behavior 1. It calls `PurgeIcons` with: - `content`: the flattened, trimmed, de-duplicated-by-filter globs, - `format` (cast to `OutputFormat`), - `included`: `args.included`. 2. If `--output` is given: `path.resolve` the output, `fs.ensureDir` its directory, and write the code with `utf-8`. 3. Otherwise it prints the code to stdout via `console.log`. The command has `showHelpOnFail(false)` and `.help()` enabled. ### Examples #### Scan HTML files and emit an ESM bundle ```bash purge-icons --content 'src/*.html' --format mjs --output output.js ``` #### Multiple sources with shorthand and format inference ```bash purge-icons -c 'index.html,src/**/*.vue' -o output.ts ``` #### Export plain JSON for other tools ```bash purge-icons -c index.html -o output.json ``` #### Output to stdout / help ```bash purge-icons --content index.html purge-icons --help ``` ``` -------------------------------- ### Usage with included icons and raw source Source: https://github.com/antfu/purge-icons Configuration that adds a raw HTML source and includes a specific icon from Font Awesome, using a remote icon source. ```ts // rollup.config.js import PurgeIcons from 'rollup-plugin-purge-icons' export default { plugins: [ PurgeIcons({ content: [ 'src/**/*.js', { extension: '.html', raw: '' }, ], included: ['fa:github'], iconSource: 'remote', }), ], } ``` -------------------------------- ### Generate icons bundle with PurgeIcons Source: https://github.com/antfu/purge-icons/blob/main/README.md Use the PurgeIcons function to scan source files and generate a bundle with inlined icon data. The content option accepts globs for files to analyze, and included whitelists icons used dynamically. The format option specifies the output format (e.g., 'mjs'). ```ts import { PurgeIconsOptions, PurgeIcons } from '@purge-icons/core' const code = await PurgeIcons({ // globs for searching source file to analyze content: [ '**/*.html', '**/*.js', '**/*.vue', // scan for .vue file as well ], // whitelist for icons that might be used dynamically included: [ 'mdi:account-circle-outline', // from Material Design Icons 'fa:camera', // from Font Awesome 4 ], format: 'mjs' }) // code is generated with inlined icons's data, bundle the file and it's done. fs.promises.writeFiles('./icons.mjs', code, 'utf-8') ``` -------------------------------- ### fetchCollection() Source: https://github.com/antfu/purge-icons Resolves a single Iconify collection (IconifyJSON) from local packages or a remote API, caches the result, and resolves aliases into full icon data. It accepts a collection id, an optional source mode, a remote data API base URL, and an optional cache object. ```APIDOC ## fetchCollection() ### Description Resolves a single Iconify collection (`IconifyJSON`) from local packages or a remote API, caches the result, and resolves aliases into full icon data. ### Method Function call (async) ### Signature ```ts export async function fetchCollection( name: CollectionId, source: IconSource = 'auto', remoteDataAPI = DEFAULT_API_PATH, cache: CollectionCache = default_cache, ): Promise ``` ### Parameters - **name** (`CollectionId`) - Required - The collection id to fetch. - **source** (`IconSource`) - Optional, default `'auto'` - `'local'`, `'remote'`, or `'auto'`. - **remoteDataAPI** (`string`) - Optional, default `DEFAULT_API_PATH` (`https://raw.githubusercontent.com/iconify/collections-json/master/json`) - Base URL for remote collection JSON. - **cache** (`CollectionCache`) - Optional, default module-level `default_cache` - Object cache keyed by collection id; memoizes results across calls. ### Returns `Promise` — the collection document with aliases resolved inline (each alias copied into `collection.icons` with signature/width overrides merged over the parent icon). The result is also written into `cache[name]`. ### Resolution order (`source`) - `'local'` or `'auto'`: tries a dynamic `import(\`@iconify-json/${name}\`)`; on failure tries `import(\`@iconify/json/json/${name}.json\`)`. If `source === 'local'` and both fail, the last error is rethrown. If `'auto'`, it falls through to remote. - `'remote'` or `'auto'` (fallback): GETs `${remoteDataAPI}/${name}.json` via `axios`, parses JSON if returned as a string, resolves aliases, caches, and returns. - If neither path ran (source is none of the handled values), throws `Unabled to fetch collection ""`. ### Rejects - For `'local'`: the underlying dynamic-import error if no local package provides the collection and source is strictly local. - For remote: the underlying `axios` error on a non-successful GET or parse error. - `Error` `` `Unabled to fetch collection "${name}"` `` — when `source` is not one of the enum branches. ### Request Example ```ts import { fetchCollection } from '@purge-icons/core' // internal module export const mdi = await fetchCollection('mdi', 'local') ``` ``` -------------------------------- ### ParseIconNames() Source: https://github.com/antfu/purge-icons Splits a list of `collection:name` icon keys into a grouped record keyed by collection id. Validates that each collection prefix is known. ```APIDOC ## ParseIconNames() ### Description Splits a list of `collection:name` icon keys into a grouped record keyed by collection id. Validates that each collection prefix is known. ### Method Function ### Signature ```ts export function ParseIconNames(icons: string[]) ``` ### Parameters - **icons** (`string[]`) - Required - Array of icon keys in `collection:name` form, e.g. `['mdi:home', 'mdi:alert', 'fa:camera']`. ### Returns `Partial>` — for each collection id, the array of icon names (the part after the delimiter). Each name is split on `DELIMITER` (`:`) with a limit of 2 parts. ### Throws `Error` with message `` `Invalid collection name: "${collection}"` `` when the prefix before `:` is not a known `CollectionId`. ### Example ```ts import { ParseIconNames } from '@purge-icons/core' const parsed = ParseIconNames(['mdi:home', 'mdi:alert', 'fa:camera']) // { mdi: ['home', 'alert'], fa: ['camera'] } ``` ``` -------------------------------- ### Extract() function signature Source: https://github.com/antfu/purge-icons Declares the async Extract function that scans configured content globs and raw contents, applies extractors, and returns unique extracted icon keys. Only content, defaultExtractor, and extractors options are used. ```ts export async function Extract(options: PurgeIconsOptions = {}) ``` -------------------------------- ### Import generated placeholder module Source: https://github.com/antfu/purge-icons In the app entry, import '@purge-icons/generated'. The plugin resolves and loads this import, replacing it with the bundled icon code. ```TypeScript // main.js import '@purge-icons/generated' ``` -------------------------------- ### ParseIconNames() function signature Source: https://github.com/antfu/purge-icons Declares the ParseIconNames function that splits icon keys into a grouped record. Throws an error for invalid collection names. ```ts export function ParseIconNames(icons: string[]) ``` -------------------------------- ### PurgeIcons constructor signature Source: https://github.com/antfu/purge-icons Constructor for PurgeIcons that accepts optional PurgeIconsOptions. The format option is hard-coded to 'cjs' internally. ```ts constructor(public readonly options: PurgeIconsOptions = {}) ``` -------------------------------- ### Re-export public modules from entry point Source: https://github.com/antfu/purge-icons The package entry point `src/index.ts` re-exports all public symbols from `types.ts`, `codegen.ts`, and `loader.ts` so they are importable directly from `@purge-icons/core`. `constants.ts` and `utils.ts` are not re-exported and are internal. ```TypeScript export * from './types' export * from './codegen' export * from './loader' ``` -------------------------------- ### CodeGen function signature Source: https://github.com/antfu/purge-icons Declares the CodeGen function that takes an array of icon keys and optional options, returning a Promise of a string. ```ts export async function CodeGen(icons: string[], options: PurgeIconsOptions = {}) ``` -------------------------------- ### CreatePlugin function signature Source: https://github.com/antfu/purge-icons Default export that returns a Rollup plugin named 'purge-icons' with resolveId and load hooks. Unlike the Vite wrapper, no default options are applied. ```ts export default function CreatePlugin(options: PurgeIconsOptions): Plugin ``` -------------------------------- ### PurgeIcons() Source: https://github.com/antfu/purge-icons/blob/main/README.md Generates a code bundle with inlined icon data based on the provided options. It scans the specified content files for icon usage and includes any whitelisted icons, returning the generated code as a string. ```APIDOC ## PurgeIcons() ### Description Generates a code bundle with inlined icon data based on the provided options. It scans the specified content files for icon usage and includes any whitelisted icons, returning the generated code as a string. ### Method PurgeIcons ### Parameters #### Options (PurgeIconsOptions) - **content** (string[] | RawContent[]) - Optional - Globs for searching source files to analyze. - **included** (string[]) - Optional - Whitelist for icons that might be used dynamically. - **extractors** (Extractor[]) - Optional - Custom extractors for icon detection. - **iconSource** (IconSource) - Optional - Icon source, defaults to 'auto'. ### Response Returns a Promise that resolves to the generated code string. ### Request Example ```ts import { PurgeIconsOptions, PurgeIcons } from '@purge-icons/core' const code = await PurgeIcons({ // globs for searching source file to analyze content: [ '**/*.html', '**/*.js', '**/*.vue', // scan for .vue file as well ], // whitelist for icons that might be used dynamically included: [ 'mdi:account-circle-outline', // from Material Design Icons 'fa:camera', // from Font Awesome 4 ], format: 'mjs' }) // code is generated with inlined icons's data, bundle the file and it's done. fs.promises.writeFiles('./icons.mjs', code, 'utf-8') ``` ``` -------------------------------- ### RawContent Source: https://github.com/antfu/purge-icons Interface representing in-memory content supplied directly instead of loading from a file glob. Contains file extension and raw content string. ```APIDOC ## RawContent ### Description In-memory content supplied directly (instead of loading from a file glob). ### Type Definition ```ts export interface RawContent { extension: string raw: string } ``` ### Fields - **extension** (`string`) - Required - File extension label (e.g. `'.html'`). - **raw** (`string`) - Required - The raw file content string. ### Used By - `PurgeIconsOptions.content` (elements that are not strings) - `Extract` (merges raw contents with files read from globs). ``` -------------------------------- ### Import @purge-icons/generated in entry file Source: https://github.com/antfu/purge-icons/blob/main/packages/purge-icons-webpack-plugin/README.md Import the generated icons module in your entry file to enable PurgeIcons. ```ts import '@purge-icons/generated' // <-- This ``` -------------------------------- ### IMPORT_PATHS constant Source: https://github.com/antfu/purge-icons Defines the import specifiers treated as the virtual 'generated icons' module. Any of these three specifiers is replaced with the bundled code. ```ts export const IMPORT_PATHS = [ '@purge-icons/generated', 'vite-plugin-purge-icons/generated', 'rollup-plugin-purge-icons/generated', ] ``` -------------------------------- ### GetIconsData() Source: https://github.com/antfu/purge-icons Fetches the collections referenced by a list of icon keys and returns a per-collection `IconifyJSON` subset containing only the requested icons. ```APIDOC ## GetIconsData() ### Description Fetches the collections referenced by a list of icon keys and returns a per-collection `IconifyJSON` subset containing only the requested icons. ### Method Async Function ### Signature ```ts export async function GetIconsData(icons: string[], options: PurgeIconsOptions = {}): Promise ``` ### Parameters - **icons** (`string[]`) - Required - Full icon keys (`collection:name`). - **options** (`PurgeIconsOptions`) - Optional - Default: `{}` - Only `iconSource` and `remoteDataAPI` are used, passed to `fetchCollection`. ### Returns `Promise` — one element per referenced collection. Each element is a `{ prefix, width, height, icons }` object where `icons` holds only the requested names from the source collection (aliases resolved by `fetchCollection`). ### Rejects Errors from `ParseIconNames` (invalid collection) or `fetchCollection` (fetch failure). See [errors](../errors.md). ### Example ```ts import { GetIconsData } from '@purge-icons/core' const data = await GetIconsData(['mdi:home'], { iconSource: 'local' }) console.log(data[0].prefix) // 'mdi' console.log(data[0].icons['home']) ``` ``` -------------------------------- ### OutputFormat type Source: https://github.com/antfu/purge-icons Valid output formats handled by CodeGen and the CLI's --format/-f choices. Each value maps to a specific generated artifact: mjs (ESM), cjs (CJS), ts (ESM-style), js (CJS-style), json (raw JSON.stringify). ```ts export type OutputFormat = 'mjs' | 'cjs' | 'ts' | 'json' | 'js' ``` -------------------------------- ### createPlugin(options?) Source: https://github.com/antfu/purge-icons The default export of the vite-plugin-purge-icons package. It creates a Vite plugin that intercepts imports of generated icon modules and inlines the PurgeIcons bundle. The plugin is pre-enforced and delegates to rollup-plugin-purge-icons. ```APIDOC ## createPlugin(options?) ### Description Creates a Vite plugin that intercepts imports of generated icon modules and inlines the PurgeIcons bundle. The plugin is pre-enforced and delegates to rollup-plugin-purge-icons. ### Signature ```ts export default function createPlugin(options: PurgeIconsOptions = {}): Plugin ``` ### Parameters - **options** (`PurgeIconsOptions`) - Optional - PurgeIcons options to apply (same shape as `@purge-icons/core`). Defaults to `{}`. ### Returns `Plugin` — a Vite/Rollup plugin with `enforce: 'pre'` that delegates to `rollup-plugin-purge-icons`' `CreatePlugin`. ### Behavior A default `PurgeIconsOptions` is merged under user options (spread order means user values win): ```ts const parsedOptions: PurgeIconsOptions = { content: ['**/*.html', '**/*.pug', '**/*.vue', '**/*.js', '**/*.ts'], iconifyImportName: '@iconify/iconify', ...options, } ``` Then `createRollupPlugin(parsedOptions)` is spread into the returned plugin, along with `enforce: 'pre'`. ### Request Example ```ts // vite.config.js import PurgeIcons from 'vite-plugin-purge-icons' export default { plugins: [ PurgeIcons(), ], } ``` ### Request Example (with custom options) ```ts // vite.config.js import PurgeIcons from 'vite-plugin-purge-icons' export default { plugins: [ PurgeIcons({ content: ['src/**/*.{html,vue,js}'], included: ['carbon:moon', 'carbon:sun'], iconSource: 'local', }), ], } ``` ### Usage Example In your app entry, import the generated placeholder module: ```ts // main.js import '@purge-icons/generated' ``` The plugin resolves and loads the `@purge-icons/generated` (and other generated) imports, replacing them with the bundled icon code. ``` -------------------------------- ### createPlugin function signature Source: https://github.com/antfu/purge-icons Default export of vite-plugin-purge-icons. Returns a Vite plugin object with enforce: 'pre' that delegates to rollup-plugin-purge-icons. ```TypeScript export default function createPlugin(options: PurgeIconsOptions = {}): Plugin ``` -------------------------------- ### PurgeIcons function signature Source: https://github.com/antfu/purge-icons Primary entry point that runs the full pipeline: Extract (scan content → icon names) → CodeGen (fetch collections → generate code string). Returns a Promise with a generated module source string, or raw JSON when `format === 'json'`. ```TypeScript export async function PurgeIcons(options: PurgeIconsOptions = {}) ``` -------------------------------- ### Default PurgeIconsOptions merge Source: https://github.com/antfu/purge-icons Default options are merged under user options; user values win due to spread order. Defaults scan HTML, pug, Vue, JS, and TS files and use '@iconify/iconify' as the import target. ```TypeScript const parsedOptions: PurgeIconsOptions = { content: ['**/*.html', '**/*.pug', '**/*.vue', '**/*.js', '**/*.ts'], iconifyImportName: '@iconify/iconify', ...options, } ``` -------------------------------- ### CodeGen - Unknown output format error Source: https://github.com/antfu/purge-icons Throws a generic Error when options.format is present and not one of the handled branches (js, cjs, mjs, ts, undefined). 'json' returns earlier, so it is not seen here. Also triggerable from the CLI for values outside its declared choices. ```ts default: throw new Error(`Unknown output format "${options.format}"`) ``` -------------------------------- ### CJS entry — index.js Source: https://github.com/antfu/purge-icons CommonJS entry point that re-exports the entire @iconify/iconify module as the package's value. ```javascript module.exports = require('@iconify/iconify') ```