@fluentui/react-icons-atomic-webpack-loader
v0.0.8
Published
Webpack loader that transforms barrel imports and re-exports from @fluentui/react-icons into atomic deep paths
Keywords
Readme
@fluentui/react-icons-atomic-webpack-loader
⚠️ 0.x — this package is in early development and follows zero-based major semver. Breaking changes may occur in minor releases until 1.0.
Webpack loader that transforms barrel imports and re-exports from @fluentui/react-icons and @fluentui/react-brand-icons into atomic deep paths for better tree-shaking and smaller bundles.
Before / After
// Before — barrel import pulls in the entire icon set
import { AddFilled, bundleIcon, useIconContext } from '@fluentui/react-icons';
import { ProjectColor } from '@fluentui/react-brand-icons';
export { ArrowLeftRegular } from '@fluentui/react-icons';
// After — each reference resolves to a small, isolated module
import { AddFilled } from '@fluentui/react-icons/svg/add';
import { bundleIcon } from '@fluentui/react-icons/utils';
import { useIconContext } from '@fluentui/react-icons/providers';
import { ProjectColor } from '@fluentui/react-brand-icons/svg/project';
export { ArrowLeftRegular } from '@fluentui/react-icons/svg/arrow-left';Usage
Add the loader to your webpack config as an enforce: 'pre' rule so it runs on the original source before any other loaders:
NOTE: Unlike most loaders, this one should NOT exclude node_modules. It needs to process files inside node_modules as well to transform barrel imports from @fluentui/react-icons and @fluentui/react-brand-icons in your third-party dependencies. Files that don't reference a supported module are skipped via a fast pre-check, so there is no meaningful overhead.
The loader also works unchanged with rspack (>=2.0.0) — the same rule shape applies, and every fixture in this package's test suite is verified against both bundlers. webpack and @rspack/core are declared as optional peer dependencies, so you only need to install the one you use.
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.[mc]?[jt]sx?$/,
enforce: 'pre',
use: ['@fluentui/react-icons-atomic-webpack-loader'],
},
// … your other rules (babel-loader, ts-loader, etc.)
],
},
};If your existing rules exclude node_modules, add a separate rule to cover dependencies:
module.exports = {
module: {
rules: [
{
test: /\.[mc]?[jt]sx?$/,
include: /[\\/]node_modules[\\/]/,
enforce: 'pre',
use: ['@fluentui/react-icons-atomic-webpack-loader'],
},
// … your other rules (babel-loader, ts-loader, etc.)
],
},
};Supported modules
| Module | Variants | Headless | Notes |
| ----------------------------- | ---------------------------- | -------------- | ----------------------------- |
| @fluentui/react-icons | svg, fonts, svg-sprite | svg, fonts | Has /providers and /utils |
| @fluentui/react-brand-icons | svg | svg | Has /utils; no /providers |
Color icons are SVG-only. Color variants (
*Color) rely on gradients that cannot be represented in an icon font, so they ship only in thesvgandsvg-spritebuilds — neverfonts. The loader reroutes color imports off font variants automatically (see Color icons below).
Options
| Option | Type | Default | Description |
| --------------------- | -------------------------------------- | ----------- | --------------------------------------------------------------------------------------- |
| iconVariant | 'svg' | 'fonts' | 'svg-sprite' | 'svg' | Variant icons resolve to. Applied to every supported module. |
| fallbackVariant | 'svg' | 'fonts' | 'svg-sprite' | undefined | Variant used for a module that does not support iconVariant (see below). |
| headless | boolean | false | Resolve to the headless (Griffel-free) build where the module ships one. |
| allowDynamicImports | boolean | false | Atomize a narrow, statically-provable subset of dynamic import() barrels (see below). |
| moduleGranularity | 'family' | 'icon' | 'family' | Give each selected icon export its own bundler module identity (see below). |
Export-level module granularity
moduleGranularity: 'icon' appends an internal, versioned resource query to
each icon-family request. The loader then processes the resolved generated ESM
family a second time and emits only the selected declaration plus its directives
and imports. This gives SplitChunks independently placeable icon modules without
publishing one physical file per export:
{
loader: '@fluentui/react-icons-atomic-webpack-loader',
options: { moduleGranularity: 'icon' },
}The loader rule must cover every source file whose Fluent barrel imports should
be rewritten, plus the generated ESM atom files under
@fluentui/react-icons and @fluentui/react-brand-icons. To rewrite imports
inside arbitrary third-party packages, omit include so matching JavaScript
and TypeScript throughout the dependency graph are processed. The loader's
source-text pre-check cheaply skips files that do not reference a supported
Fluent icon package.
For the lowest rule-matching overhead, applications that only rewrite their own source and a known set of dependencies can use a targeted include:
const path = require('path');
{
test: /\.[mc]?[jt]sx?$/,
include: [
path.resolve(__dirname, 'src'),
path.dirname(require.resolve('known-dependency/package.json')),
/node_modules[\\/]@fluentui[\\/]react-(?:brand-)?icons[\\/]lib[\\/]atoms[\\/]/,
],
enforce: 'pre',
use: [
{
loader: '@fluentui/react-icons-atomic-webpack-loader',
options: { moduleGranularity: 'icon' },
},
],
}The first pass rewrites application imports to query-addressed family requests. The bundler resolves each request to a physical generated atom file, then applies the same loader rule again to emit the selected virtual module. Webpack and Rspack do not interpret the selector query themselves. If the atom directory is excluded, the second pass cannot run and the full physical family source is loaded under the queried identity. The loader cannot diagnose that misconfiguration because it is never invoked for that resource.
Every third-party importer that should be rewritten must be represented in the
targeted list; otherwise use the comprehensive rule without include.
Utilities, providers, and helper modules remain canonical and unqueried.
Opt out high-cardinality application areas
moduleGranularity is selected per loader rule, so an application can use icon
granularity for most source files while retaining family granularity for an
area that intentionally uses many or all icons, such as an icon picker. This
avoids creating thousands of virtual module and cache entries where independent
chunk placement provides little benefit:
const path = require('path');
const loader = require.resolve('@fluentui/react-icons-atomic-webpack-loader');
const appSource = path.resolve(__dirname, 'src');
const iconPickerSource = path.resolve(appSource, 'icon-picker');
const fluentAtoms = /node_modules[\\/]@fluentui[\\/]react-(?:brand-)?icons[\\/]lib[\\/]atoms[\\/]/;
module.exports = {
module: {
rules: [
{
test: /\.[mc]?[jt]sx?$/,
include: [appSource, fluentAtoms],
exclude: iconPickerSource,
enforce: 'pre',
loader,
options: { moduleGranularity: 'icon' },
},
{
test: /\.[mc]?[jt]sx?$/,
include: iconPickerSource,
enforce: 'pre',
loader,
options: { moduleGranularity: 'family' },
},
],
},
};The generated atom directory stays in the icon rule because query-selected
requests need the loader's second pass. The moduleGranularity option is not
consulted during that pass: the __fluentIcon query already identifies the
selection request. Unqueried atom modules produced by the family-mode rule pass
through unchanged.
For a runtime picker that truly needs the complete export set, placing an
unatomized import('@fluentui/react-icons') behind a lazy boundary keeps that
cost in the picker's async chunk. Dynamic barrel imports are intentionally not
expanded into thousands of selected modules.
Direct named family imports are selected without changing their explicit
strategy, so /svg/add stays SVG even when iconVariant: 'fonts' is configured.
Namespace/default direct imports and imports whose family membership cannot be
proven retain family behavior with a warning. CommonJS resources remain
family-level; malformed or stale selector queries fail the build.
Font and SVG-sprite icon granularity requires compatible releases of the
corresponding subsetting plugin. A compilation-level protocol handshake fails
closed if the plugin is absent or query-unaware. Revert to
moduleGranularity: 'family' for immediate rollback.
Each selected export becomes a module-graph and persistent-cache entry, and each
selected React Server Component module repeats its "use client" directive.
Measure cold/warm build time, peak memory, cache size, module count, and route
ownership before rollout. SplitChunks rules matching icon atom resources should
account for resourceQuery rather than assuming one family module.
The loader skips source-map generation when the bundler disables source maps. When enabled, importer and selector maps are composed with any incoming map. Repository contributors can run the repeatable 5,000-export microbenchmark with:
yarn workspace @fluentui/react-icons-atomic-webpack-loader benchmarkOverride its scale with ICON_BENCHMARK_EXPORTS and
ICON_BENCHMARK_ITERATIONS. The benchmark reports fast-skip and importer
rewrite timing, source-map cost, selector emissions, unique physical parses,
cache hits, cache entries, and RSS change (the process's resident memory at the
end of a scenario minus its resident memory at the start). It measures loader work only;
consumer validation must additionally record bundler module counts,
persistent-cache size, and route ownership.
Set ICON_BENCHMARK_JSON=1 for machine-readable output. The benchmark is not a
CI gate because wall-clock and RSS measurements vary across shared runners.
Variant resolution & fallbackVariant
iconVariant is applied to every supported module referenced in a file. Because not every module ships every variant (for example @fluentui/react-brand-icons only ships svg), the loader resolves the variant per module:
- If the module supports
iconVariant, it is used. - Otherwise, if
fallbackVariantis set and supported by the module, it is used. - Otherwise, if
fallbackVariantis set but also unsupported, the loader emits a warning and falls back tosvg. - Otherwise (no
fallbackVariant), the loader fails with a descriptive error.
Resolution is lazy and per file: only modules actually imported in a given file are checked, so a file that imports only @fluentui/react-icons never errors about brand icons.
// Resolve system icons to fonts, but keep brand icons on svg (their only variant).
{
loader: '@fluentui/react-icons-atomic-webpack-loader',
options: {
iconVariant: 'fonts',
fallbackVariant: 'svg',
},
}Color icons
Color variants (*Color, e.g. AddCircleColor) are SVG-only — their gradients cannot be represented in an icon font, so the fonts build ships no color glyphs. When a color icon is imported under a color-less variant (iconVariant: 'fonts'), the loader reroutes just that import to a color-capable variant, following the same precedence as above (constrained to svg / svg-sprite), and emits a warning:
- If
iconVariantis already color-capable (svg/svg-sprite), the color import is left on it — no reroute, no warning. - Otherwise, if
fallbackVariantis set and color-capable, it is used (e.g.svg-sprite). - Otherwise the loader falls back to
svg.
Rerouting is per specifier, so color and non-color icons in the same statement resolve independently:
// iconVariant: 'fonts'
import { AddFilled, AddCircleColor } from '@fluentui/react-icons';
// →
import { AddFilled } from '@fluentui/react-icons/fonts/add';
import { AddCircleColor } from '@fluentui/react-icons/svg/add-circle';Color icons are deprecated. See the user guidance.
Using font icons
{
test: /\.[mc]?[jt]sx?$/,
enforce: 'pre',
use: [
{
loader: '@fluentui/react-icons-atomic-webpack-loader',
options: {
iconVariant: 'fonts',
},
},
],
}This changes icon resolution from @fluentui/react-icons/svg/* to @fluentui/react-icons/fonts/*. Non-icon exports (utils, providers) are unaffected.
Color icons have no font build and are rerouted to
svg(orsvg-sprite) automatically — see Color icons.
Using the headless API
{
loader: '@fluentui/react-icons-atomic-webpack-loader',
options: {
iconVariant: 'fonts',
headless: true,
},
}With the example above:
| Import | Resolves to |
| ------------------- | ------------------------------------------ |
| AddFilled | @fluentui/react-icons/headless/fonts/add |
| bundleIcon (util) | @fluentui/react-icons/headless/utils |
| useIconContext | @fluentui/react-icons/providers (shared) |
Notes:
- Best-effort per module: a module without a headless build for the resolved variant degrades to its standard (Griffel) implementation with a warning rather than failing the build. This applies to headless
svg-sprite(not generated yet). - Version requirement: headless
@fluentui/react-brand-iconsrequires>= 2.0.206. The loader rewrites imports statically and does not check the installed version, so an older brand-icons will fail to resolve the/headless/*entries at build time. - Context is shared:
useIconContext/IconDirectionContextProvideralways resolve to@fluentui/react-icons/providers— it is framework-agnostic and reused by both APIs. - CSS is your responsibility: the loader only rewrites component/utility imports. You must still import the headless CSS in your app entry point:
import '@fluentui/react-icons/headless/styles.css'; // and, for font icons: import '@fluentui/react-icons/headless/fonts/styles.css';
Using SVG sprite icons
{
test: /\.[mc]?[jt]sx?$/,
enforce: 'pre',
use: [
{
loader: '@fluentui/react-icons-atomic-webpack-loader',
options: {
iconVariant: 'svg-sprite',
},
},
],
}This changes icon resolution from @fluentui/react-icons/svg/* to @fluentui/react-icons/svg-sprite/*. Non-icon exports (utils, providers) are unaffected.
How it works
The loader parses each module and rewrites import and re-export declarations that reference a supported module. Each named specifier is routed to an atomic subpath based on its name:
Resolution flow
Each named specifier is resolved independently, so color and non-color icons — even within the same statement — can land on different variants.
flowchart TD
A["Named specifier from a supported module"] --> B{"Icon name? ends in Regular / Filled / Light / Color"}
B -->|"context / hook"| P["/providers"]
B -->|"utility"| U["/utils"]
B -->|"yes"| V{"Module supports iconVariant?"}
V -->|"yes"| R["variant = iconVariant"]
V -->|"no"| F{"fallbackVariant set?"}
F -->|"no"| ERR["Error: import left untouched, set fallbackVariant"]
F -->|"yes, supported"| R2["variant = fallbackVariant"]
F -->|"yes, unsupported"| RS["variant = svg (warning)"]
R --> C{"Color icon?"}
R2 --> C
RS --> C
C -->|"no"| H{"headless requested and available for variant?"}
C -->|"yes, already color-capable: svg / svg-sprite"| H
C -->|"yes, color-less variant: fonts"| CC["reroute to first color-capable of iconVariant, fallbackVariant, svg (warning)"]
CC --> H
H -->|"yes"| HP["prefix with /headless"]
H -->|"no / not available (warning)"| STD["standard build"]
HP --> OUT["resolved atomic path"]
STD --> OUTSteps marked "(warning)" emit a build warning — a best-effort degrade rather than a hard failure.
@fluentui/react-icons
| Export type | Example | Resolved path |
| -------------- | ------------------------------------------------ | -------------------------------------------------------------------- |
| Icon component | AddFilled, ArrowLeftRegular | @fluentui/react-icons/svg/add (or /fonts/add, /svg-sprite/add) |
| Context / hook | useIconContext, IconDirectionContextProvider | @fluentui/react-icons/providers |
| Utility | bundleIcon, createFluentIcon | @fluentui/react-icons/utils |
@fluentui/react-brand-icons
| Export type | Example | Resolved path |
| -------------- | ----------------------------------------- | ----------------------------------------- |
| Icon component | ProjectColor, CalendarTaskbar20Filled | @fluentui/react-brand-icons/svg/project |
| Utility | bundleIcon, createFluentIcon | @fluentui/react-brand-icons/utils |
Files that don't reference a supported module are passed through untouched (fast pre-check).
Limitations
Export-level selection applies to generated ESM atoms only. Existing unqueried CommonJS deep imports continue to use family-level behavior.
Dynamic imports are not atomized
The loader only rewrites static import / export … from declarations. A dynamic import() of a barrel cannot be atomized, because the returned module-namespace object is a runtime value whose usage the loader cannot statically prove:
// ⚠️ Not rewritten — the ENTIRE icon set is pulled into the async chunk.
const { AddFilled } = await import('@fluentui/react-icons');
React.lazy(() => import('@fluentui/react-icons'));When it detects a dynamic import of a supported barrel, the loader emits a warning. Import the atomic path directly instead — then you lazy-load only the icons you use:
// ✅ Only this icon lands in the async chunk.
const { AddFilled } = await import('@fluentui/react-icons/svg/add');Alternatively, move the icons behind a local module that statically imports them; the loader atomizes that module, and only your lazy chunk pays for what it uses.
The same applies to full-barrel subpaths (
@fluentui/react-icons/svg,@fluentui/react-icons/fonts) — dynamically importing those also bundles the whole set. Always target a per-icon atomic path.
Opt-in: allowDynamicImports
Prefer a dedicated module of static imports. The most robust pattern is a small module that statically imports the icons you need and is itself lazy-loaded (
const { AddFilled } = await import('./lazy-icons')). Static imports are atomized unconditionally, tree-shake predictably, and avoid every gotcha below. Reach forallowDynamicImportsonly when refactoring to that pattern isn't practical.
With allowDynamicImports: true, the loader additionally rewrites a narrow,
statically-provable subset of dynamic barrel imports into atomic ones. Only two
call-site shapes qualify — where the imported names are literals at the import():
// await + object destructure
const { AddFilled } = await import('@fluentui/react-icons');
// → const { AddFilled } = await import('@fluentui/react-icons/svg/add');
// .then + object-pattern callback param
import('@fluentui/react-icons').then(({ AddFilled }) => …);
// → import('@fluentui/react-icons/svg/add').then(({ AddFilled }) => …);Names from the same atom are grouped into one import; names from different
atoms become a positional Promise.all([...]):
const { AddFilled, ArrowLeftRegular } = await import('@fluentui/react-icons');
// →
const [{ AddFilled }, { ArrowLeftRegular }] = await Promise.all([
import('@fluentui/react-icons/svg/add'),
import('@fluentui/react-icons/svg/arrow-left'),
]);It honors iconVariant / fallbackVariant / headless and per-name color
rerouting exactly like static imports.
Gotchas — what is not rewritten (left untouched, still warns)
- Namespace binding:
const ns = await import('@fluentui/react-icons')—nsis a runtime object; usage isn't statically known, so the whole set ships. .then(m => m.AddFilled): namespace parameter + member access — not a destructure, so the names aren't visible at the call site.- Rest / computed / default / nested patterns:
{ AddFilled, ...rest },{ [name]: icon },{ AddFilled = fallback },{ Add: { … } }. - Non-literal specifiers:
import(pkg), template interpolation, or a promise stored in a variable and.then-ed elsewhere.
For any of these the loader leaves your code as-is and emits the standard "cannot be atomized" warning — the safe default.
⚠️ The
Promise.allrewrite changes the emitted runtime structure (parallel chunk loading, positional destructuring). It's semantically equivalent for the supported shapes, but if you depend on the exact expression shape, prefer the dedicated-module pattern above.
Requirements
webpack>= 5@fluentui/react-icons>= 2 (with atomic subpath exports)@fluentui/react-brand-icons(with atomic subpath exports), if used>= 2.0.206when usingheadless: true— earlier versions do not ship the/headless/svg/*and/headless/utilsentries, so the loader's rewritten imports will fail to resolve.
