@fluentui/react-icons-font-subsetting-webpack-plugin 2.0.337 → 2.0.339

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @fluentui/react-icons-font-subsetting-webpack-plugin
2
2
 
3
- This package includes a plugin for `webpack@>=5.0.0` to subset the icon font files used by `@fluentui/react-icons` when using font-based icon implementations.
3
+ This package includes a plugin for `webpack@>=5.0.0` and `@rspack/core@>=2.1.0` to subset the icon font files used by `@fluentui/react-icons` when using font-based icon implementations.
4
4
 
5
- If `optimization.usedExports` is enabled (as it is by default in webpack `production` mode), this plugin will subset the font files to only include the glyphs actually used by your build.
5
+ If `optimization.usedExports` is enabled (as it is by default in `production` mode), this plugin will subset the font files to only include the glyphs actually used by your build.
6
6
 
7
7
  ## Supported Import Patterns
8
8
 
@@ -94,3 +94,35 @@ module.exports = {
94
94
  ],
95
95
  };
96
96
  ```
97
+
98
+ ### With rspack
99
+
100
+ The plugin is bundler-agnostic and works unchanged in rspack — the same configuration applies:
101
+
102
+ ```js
103
+ // rspack.config.js
104
+ const {
105
+ default: FluentUIReactIconsFontSubsettingPlugin,
106
+ } = require('@fluentui/react-icons-font-subsetting-webpack-plugin');
107
+
108
+ module.exports = {
109
+ module: {
110
+ rules: [
111
+ {
112
+ test: /\.(ttf|woff2?)$/,
113
+ type: 'asset',
114
+ },
115
+ ],
116
+ },
117
+ plugins: [new FluentUIReactIconsFontSubsettingPlugin()],
118
+ };
119
+ ```
120
+
121
+ Two rspack-specific notes:
122
+
123
+ - For the headless import pattern, use `rspack.CssExtractRspackPlugin` instead of `mini-css-extract-plugin`, which is not compatible with rspack.
124
+ - `webpack` and `@rspack/core` are both declared as **optional** peer dependencies, so you only need to install the bundler you actually use.
125
+
126
+ rspack `>=2.1.0` is required because subsetting reads the module graph: `moduleGraph.getUsedExports()`
127
+ was exposed to the JS API in rspack 2.0.0, and `moduleGraph.getProvidedExports()` — which this plugin
128
+ relies on to subset namespace imports (`import * as …`) — only landed in 2.1.0.
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Hand-maintained description of the bundler APIs this plugin touches.
3
+ *
4
+ * Deliberately not `import type ... from 'webpack'`: both bundlers are optional peers, so
5
+ * referencing webpack's types here would leak into the generated `.d.ts` and break type-checking
6
+ * for consumers who only installed `@rspack/core`.
7
+ *
8
+ * Every member is intentionally *wider* than the corresponding webpack and rspack type, so both
9
+ * real compilers remain assignable to `BundlerCompiler`. That contravariance is what lets `apply()`
10
+ * take a typed parameter instead of `unknown`. `test/types.conformance.ts` fails to compile if
11
+ * either bundler ever drifts out of these bounds.
12
+ */
13
+ /// <reference types="node" />
14
+ /// <reference types="node" />
15
+ export interface BundlerSource {
16
+ source(): string | Buffer;
17
+ }
18
+ /** `type` is present on both bundlers' modules; `resource` only on normal modules. */
19
+ export interface BundlerModule {
20
+ readonly type?: string;
21
+ readonly resource?: string;
22
+ }
23
+ export interface BundlerNormalModule extends BundlerModule {
24
+ readonly resource: string;
25
+ }
26
+ export interface BundlerModuleGraph {
27
+ /** webpack passes a `RuntimeSpec`; rspack requires explicit runtime names. */
28
+ getUsedExports(module: BundlerModule, runtime: string | string[] | ReadonlySet<string> | undefined): ReadonlySet<string> | readonly string[] | boolean | null;
29
+ /** Exposed to rspack's JS API only in 2.1.0, which is what sets the `@rspack/core` peer floor. */
30
+ getProvidedExports(module: BundlerModule): readonly string[] | boolean | null;
31
+ }
32
+ export interface BundlerAsset {
33
+ name: string;
34
+ source: BundlerSource;
35
+ info?: {
36
+ sourceFilename?: string;
37
+ };
38
+ }
39
+ export interface BundlerCompilation {
40
+ hooks: {
41
+ processAssets: {
42
+ tapPromise(options: {
43
+ name: string;
44
+ stage: number;
45
+ }, fn: () => Promise<void>): void;
46
+ };
47
+ };
48
+ modules: Iterable<BundlerModule>;
49
+ moduleGraph: BundlerModuleGraph;
50
+ entrypoints: ReadonlyMap<string, unknown>;
51
+ warnings: Error[];
52
+ getAsset(name: string): BundlerAsset | undefined | void;
53
+ getAssets(): readonly BundlerAsset[];
54
+ /**
55
+ * `any` is load-bearing: both bundlers accept a full `webpack-sources` `Source` here, and only
56
+ * `any` is assignable to that, which is what keeps real compilers assignable to this interface.
57
+ * The value passed is always one the bundler itself constructed via `sources.RawSource`.
58
+ */
59
+ updateAsset(name: string, source: any): void;
60
+ }
61
+ export interface BundlerCompiler {
62
+ context: string;
63
+ /** rspack aliases this to its own namespace, which is why no bundler is imported at runtime. */
64
+ webpack: {
65
+ Compilation: {
66
+ PROCESS_ASSETS_STAGE_OPTIMIZE: number;
67
+ };
68
+ sources: {
69
+ RawSource: new (value: string | Buffer, ...rest: any[]) => BundlerSource;
70
+ };
71
+ };
72
+ hooks: {
73
+ compilation: {
74
+ tap(name: string, fn: (compilation: BundlerCompilation) => void): void;
75
+ };
76
+ };
77
+ }
78
+ /** The shape both bundlers require of a plugin instance. */
79
+ export interface BundlerPlugin {
80
+ apply(compiler: BundlerCompiler): void;
81
+ }
82
+ export type BundlerRawSource = BundlerCompiler['webpack']['sources']['RawSource'];
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ /**
3
+ * Hand-maintained description of the bundler APIs this plugin touches.
4
+ *
5
+ * Deliberately not `import type ... from 'webpack'`: both bundlers are optional peers, so
6
+ * referencing webpack's types here would leak into the generated `.d.ts` and break type-checking
7
+ * for consumers who only installed `@rspack/core`.
8
+ *
9
+ * Every member is intentionally *wider* than the corresponding webpack and rspack type, so both
10
+ * real compilers remain assignable to `BundlerCompiler`. That contravariance is what lets `apply()`
11
+ * take a typed parameter instead of `unknown`. `test/types.conformance.ts` fails to compile if
12
+ * either bundler ever drifts out of these bounds.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
package/lib/index.d.ts CHANGED
@@ -1,17 +1,21 @@
1
- import * as webpack from 'webpack';
2
- export default class FluentUIReactIconsFontSubsettingPlugin implements webpack.WebpackPluginInstance {
1
+ import type { BundlerCompiler, BundlerPlugin } from './bundler-api';
2
+ export type * from './bundler-api';
3
+ export default class FluentUIReactIconsFontSubsettingPlugin implements BundlerPlugin {
3
4
  /**
4
- * Entry point for the Webpack plugin that registers hooks to perform font subsetting for `@fluentui/react-icons`.
5
+ * Entry point for the bundler plugin that registers hooks to perform font subsetting for `@fluentui/react-icons`.
5
6
  *
6
- * This method is executed **once** by Webpack when the plugin is initialized during the compiler's
7
- * bootstrap phase. The internal logic hooked into `optimizeAssets` is executed **once per compilation**
8
- * (whenever Webpack processes the module graph and prepares to output assets) during the
7
+ * This method is executed **once** by the bundler when the plugin is initialized during the compiler's
8
+ * bootstrap phase. The internal logic hooked into `processAssets` is executed **once per compilation**
9
+ * (whenever the bundler processes the module graph and prepares to output assets) during the
9
10
  * asset optimization stage.
10
11
  *
11
12
  * It analyzes the module graph to determine which specific icons are used from Fluent UI icon packages
12
13
  * and triggers font subsetting to remove unused glyphs from the final output assets.
13
14
  *
14
- * @param compiler - The Webpack compiler instance.
15
+ * Works with both webpack 5 and rspack. All bundler internals are reached through `compiler.webpack`,
16
+ * which rspack aliases to its own namespace, so neither bundler is imported at runtime.
17
+ *
18
+ * @param compiler - The webpack or rspack compiler instance.
15
19
  */
16
- apply(compiler: webpack.Compiler): void;
20
+ apply(compiler: BundlerCompiler): void;
17
21
  }
package/lib/index.js CHANGED
@@ -1,32 +1,8 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
26
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
4
  };
28
5
  Object.defineProperty(exports, "__esModule", { value: true });
29
- const webpack = __importStar(require("webpack"));
30
6
  const subset_font_1 = __importDefault(require("subset-font"));
31
7
  const path_1 = require("path");
32
8
  const promises_1 = require("fs/promises");
@@ -49,26 +25,31 @@ const FONT_EXTENSIONS = ['.ttf', '.woff', '.woff2'];
49
25
  const REACT_ICONS_FONT_MODULE_IMPORT_PATTERN = /react-icons[\/\\]lib(-cjs)?[\/\\](fonts[\/\\](sizedIcons|icons)[\/\\]chunk-\d+|atoms[\/\\](headless-)?fonts[\/\\][\w-]+)\.c?js$/;
50
26
  class FluentUIReactIconsFontSubsettingPlugin {
51
27
  /**
52
- * Entry point for the Webpack plugin that registers hooks to perform font subsetting for `@fluentui/react-icons`.
28
+ * Entry point for the bundler plugin that registers hooks to perform font subsetting for `@fluentui/react-icons`.
53
29
  *
54
- * This method is executed **once** by Webpack when the plugin is initialized during the compiler's
55
- * bootstrap phase. The internal logic hooked into `optimizeAssets` is executed **once per compilation**
56
- * (whenever Webpack processes the module graph and prepares to output assets) during the
30
+ * This method is executed **once** by the bundler when the plugin is initialized during the compiler's
31
+ * bootstrap phase. The internal logic hooked into `processAssets` is executed **once per compilation**
32
+ * (whenever the bundler processes the module graph and prepares to output assets) during the
57
33
  * asset optimization stage.
58
34
  *
59
35
  * It analyzes the module graph to determine which specific icons are used from Fluent UI icon packages
60
36
  * and triggers font subsetting to remove unused glyphs from the final output assets.
61
37
  *
62
- * @param compiler - The Webpack compiler instance.
38
+ * Works with both webpack 5 and rspack. All bundler internals are reached through `compiler.webpack`,
39
+ * which rspack aliases to its own namespace, so neither bundler is imported at runtime.
40
+ *
41
+ * @param compiler - The webpack or rspack compiler instance.
63
42
  */
64
43
  apply(compiler) {
44
+ const { Compilation, sources } = compiler.webpack;
65
45
  compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
66
- compilation.hooks.optimizeAssets.tapPromise(PLUGIN_NAME, async () => {
46
+ compilation.hooks.processAssets.tapPromise({ name: PLUGIN_NAME, stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE }, async () => {
47
+ const runtime = getRuntimeSpec(compiler, compilation);
67
48
  // There could be multiple instances of `@fluentui/react-icons`, and they need to be subset separately
68
49
  const packageToUsedFontExports = new Map();
69
50
  for (const m of compilation.modules) {
70
51
  if (isFluentUIReactFontChunk(m)) {
71
- const icons = resolveUsedIconExports(m, compilation.moduleGraph);
52
+ const icons = resolveUsedIconExports(m, compilation.moduleGraph, runtime);
72
53
  if (icons === null) {
73
54
  continue;
74
55
  }
@@ -82,8 +63,16 @@ class FluentUIReactIconsFontSubsettingPlugin {
82
63
  }
83
64
  const optimizationPromises = [];
84
65
  for (const [pkgLibPath, usedExports] of packageToUsedFontExports) {
85
- for (const { assetName, codepoints: codepointMap } of await getFontAssetsAndCodepoints(pkgLibPath, compilation)) {
86
- optimizationPromises.push(optimizeFontAsset(codepointMap, usedExports, compilation, assetName));
66
+ const fontAssets = await getFontAssetsAndCodepoints(pkgLibPath, compilation, compiler.context);
67
+ if (fontAssets.length === 0) {
68
+ // Loud failure: silently shipping an un-subset font is worse than a broken build.
69
+ compilation.warnings.push(new Error(`${PLUGIN_NAME}: found used icon fonts in "${pkgLibPath}" but could not map any font module ` +
70
+ `to an emitted asset. Fonts will NOT be subset. Ensure a \`type: 'asset'\` (or 'asset/resource') ` +
71
+ `module rule matches /\\.(ttf|woff2?)$/.`));
72
+ continue;
73
+ }
74
+ for (const { assetName, codepoints: codepointMap } of fontAssets) {
75
+ optimizationPromises.push(optimizeFontAsset(codepointMap, usedExports, compilation, assetName, sources.RawSource));
87
76
  }
88
77
  }
89
78
  // IMPORTANT: actually await all subsetting work
@@ -93,7 +82,22 @@ class FluentUIReactIconsFontSubsettingPlugin {
93
82
  }
94
83
  }
95
84
  exports.default = FluentUIReactIconsFontSubsettingPlugin;
96
- async function optimizeFontAsset(codepointMap, usedExports, compilation, assetName) {
85
+ /**
86
+ * Resolves the runtime to query used-exports information for.
87
+ *
88
+ * webpack accepts `undefined` to mean "merged across all runtimes", but rspack's binding requires an
89
+ * explicit `string | string[]`, so entrypoint names are passed instead.
90
+ */
91
+ function getRuntimeSpec(compiler, compilation) {
92
+ if (!isRspack(compiler)) {
93
+ return undefined;
94
+ }
95
+ return Array.from(compilation.entrypoints.keys());
96
+ }
97
+ function isRspack(compiler) {
98
+ return 'rspack' in compiler;
99
+ }
100
+ async function optimizeFontAsset(codepointMap, usedExports, compilation, assetName, RawSource) {
97
101
  // Build subset text from the used exports set (usually small) instead of scanning all glyphs
98
102
  let subsetText = '';
99
103
  for (const glyphName of usedExports) {
@@ -102,13 +106,18 @@ async function optimizeFontAsset(codepointMap, usedExports, compilation, assetNa
102
106
  subsetText += String.fromCodePoint(codepoint);
103
107
  }
104
108
  }
105
- let source = compilation.assets[assetName].source();
109
+ const asset = compilation.getAsset(assetName);
110
+ if (!asset) {
111
+ return;
112
+ }
113
+ let source = asset.source.source();
106
114
  if (typeof source === 'string') {
107
115
  source = Buffer.from(source);
108
116
  }
109
- compilation.assets[assetName] = new webpack.sources.RawSource(await (0, subset_font_1.default)(source, subsetText, {
117
+ // rspack's `compilation.assets` is a read-only proxy, so writes must go through `updateAsset`.
118
+ compilation.updateAsset(assetName, new RawSource(await (0, subset_font_1.default)(source, subsetText, {
110
119
  targetFormat: getTargetFormat(assetName),
111
- }));
120
+ })));
112
121
  }
113
122
  function getTargetFormat(assetName) {
114
123
  switch ((0, path_1.extname)(assetName)) {
@@ -123,14 +132,14 @@ function getTargetFormat(assetName) {
123
132
  /**
124
133
  * Resolves the set of icon export names that are actually consumed from a font chunk module.
125
134
  *
126
- * Uses Webpack's `moduleGraph.getUsedExports()` which returns one of four shapes:
135
+ * Uses the bundler's `moduleGraph.getUsedExports()` which returns one of four shapes:
127
136
  *
128
- * | Return value | Meaning | Action |
129
- * | --------------- | ------------------------------------------------------------------ | ------------------------------------------ |
130
- * | `null` | `optimization.usedExports` is disabled — no usage info available | Skip (cannot determine which glyphs to keep)|
131
- * | `false` | Module has zero consumers — nothing is imported from it | Skip (nothing to subset) |
132
- * | `true` | All exports are consumed (e.g. `import * as ns from '...'`) | Fall back to `getProvidedExports()` ¹ |
133
- * | `Set<string>` | Exact set of named exports that are consumed | Use directly for subsetting |
137
+ * | Return value | Meaning | Action |
138
+ * | ------------------------ | ------------------------------------------------------------------ | ------------------------------------------ |
139
+ * | `null` | `optimization.usedExports` is disabled — no usage info available | Skip (cannot determine which glyphs to keep)|
140
+ * | `false` | Module has zero consumers — nothing is imported from it | Skip (nothing to subset) |
141
+ * | `true` | All exports are consumed (e.g. `import * as ns from '...'`) | Fall back to `getProvidedExports()` ¹ |
142
+ * | `Set<string>`/`string[]` | Exact set of named exports that are consumed | Use directly for subsetting |
134
143
  *
135
144
  * ¹ When all exports are marked as used we can still subset: `getProvidedExports()` tells us
136
145
  * which exports this specific module **declares** (not the entire font), so we subset the font
@@ -144,8 +153,8 @@ function getTargetFormat(assetName) {
144
153
  *
145
154
  * Returns `null` when subsetting cannot be performed, so the caller can skip the module.
146
155
  */
147
- function resolveUsedIconExports(m, moduleGraph) {
148
- const usedModuleExports = moduleGraph.getUsedExports(m, undefined);
156
+ function resolveUsedIconExports(m, moduleGraph, runtime) {
157
+ const usedModuleExports = moduleGraph.getUsedExports(m, runtime);
149
158
  if (usedModuleExports === null) {
150
159
  // No info on used exports (optimization.usedExports is disabled) - subsetting requires knowing exactly which exports are used.
151
160
  return null;
@@ -159,17 +168,21 @@ function resolveUsedIconExports(m, moduleGraph) {
159
168
  // Retrieve statically-provided exports from the module graph so we can subset to exactly
160
169
  // the glyphs this module declares (rather than the full font or nothing).
161
170
  const providedExports = moduleGraph.getProvidedExports(m);
162
- if (providedExports === null || providedExports === true) {
171
+ if (providedExports === null || typeof providedExports === 'boolean') {
163
172
  // Provided exports not statically known (optimization.providedExports disabled) - skip.
164
173
  return null;
165
174
  }
166
- return providedExports;
175
+ return [...providedExports];
167
176
  }
168
- // usedModuleExports is a Set<string> with the exact named exports that are used.
177
+ // usedModuleExports is a Set<string> (webpack) or string[] (rspack) with the exact named exports that are used.
169
178
  return Array.from(usedModuleExports);
170
179
  }
180
+ /**
181
+ * rspack modules are proxies over Rust objects and are never instances of webpack's `NormalModule`,
182
+ * so presence of `resource` is used as the portable discriminator.
183
+ */
171
184
  function isNormalModule(m) {
172
- return m instanceof webpack.NormalModule;
185
+ return typeof m.resource === 'string';
173
186
  }
174
187
  function isFluentUIReactFontChunk(m) {
175
188
  if (!isNormalModule(m)) {
@@ -185,7 +198,13 @@ function isFluentUIReactFontChunk(m) {
185
198
  }
186
199
  return REACT_ICONS_FONT_MODULE_IMPORT_PATTERN.test(resource);
187
200
  }
188
- async function getFontAssetsAndCodepoints(pkgLibPath, compilation) {
201
+ /**
202
+ * Maps emitted font assets back to their codepoint tables.
203
+ *
204
+ * Assets are matched through `AssetInfo.sourceFilename` (the originating file, relative to the compiler
205
+ * context) rather than the module's `buildInfo`, which rspack leaves empty for asset modules.
206
+ */
207
+ async function getFontAssetsAndCodepoints(pkgLibPath, compilation, context) {
189
208
  const utilsFontsFolder = (0, path_1.resolve)(pkgLibPath, 'utils/fonts');
190
209
  const codepoints = Object.fromEntries(await Promise.all(FONT_FILES_BASE_NAMES.map(async (fontBaseName) => [
191
210
  fontBaseName,
@@ -193,12 +212,14 @@ async function getFontAssetsAndCodepoints(pkgLibPath, compilation) {
193
212
  ])));
194
213
  const fontPaths = new Map(FONT_FILES_BASE_NAMES.flatMap((fontBaseName) => FONT_EXTENSIONS.map((ext) => [(0, path_1.resolve)(utilsFontsFolder, `${fontBaseName}${ext}`), codepoints[fontBaseName]])));
195
214
  const result = [];
196
- for (const m of compilation.modules) {
197
- if (isNormalModule(m) && fontPaths.has(m.resource)) {
198
- const assetName = m.buildInfo?.filename;
199
- if (assetName) {
200
- result.push({ assetName, codepoints: fontPaths.get(m.resource) });
201
- }
215
+ for (const { name: assetName, info } of compilation.getAssets()) {
216
+ const sourceFilename = info?.sourceFilename;
217
+ if (!sourceFilename) {
218
+ continue;
219
+ }
220
+ const codepointsForAsset = fontPaths.get((0, path_1.resolve)(context, sourceFilename));
221
+ if (codepointsForAsset) {
222
+ result.push({ assetName, codepoints: codepointsForAsset });
202
223
  }
203
224
  }
204
225
  return result;
package/package.json CHANGED
@@ -1,10 +1,13 @@
1
1
  {
2
2
  "name": "@fluentui/react-icons-font-subsetting-webpack-plugin",
3
- "version": "2.0.337",
3
+ "version": "2.0.339",
4
4
  "description": "Webpack plugin to subset the icon fonts used by @fluentui/react-icons based on which icons are used.",
5
5
  "main": "lib/index.js",
6
6
  "scripts": {
7
- "test": "yarn run -T webpack -c test/webpack.config.js",
7
+ "test": "yarn run test:types && node test/run.js --bundler all",
8
+ "test:types": "yarn run -T tsc -p test/tsconfig.conformance.json",
9
+ "test:webpack": "node test/run.js --bundler webpack",
10
+ "test:rspack": "node test/run.js --bundler rspack",
8
11
  "dev": "yarn run -T webpack serve -c test/webpack.config.js --open",
9
12
  "build": "yarn run -T tsc -p .",
10
13
  "lint": "yarn run -T eslint package.json"
@@ -30,8 +33,17 @@
30
33
  "subset-font": "^1.4.0"
31
34
  },
32
35
  "peerDependencies": {
36
+ "@rspack/core": ">=2.1.0",
33
37
  "webpack": ">=5.0.0"
34
38
  },
39
+ "peerDependenciesMeta": {
40
+ "@rspack/core": {
41
+ "optional": true
42
+ },
43
+ "webpack": {
44
+ "optional": true
45
+ }
46
+ },
35
47
  "files": [
36
48
  "lib/*"
37
49
  ]