@fluentui/react-icons-font-subsetting-webpack-plugin 2.0.338 → 2.0.340
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 +65 -2
- package/lib/bundler-api.d.ts +88 -0
- package/lib/bundler-api.js +14 -0
- package/lib/index.d.ts +23 -8
- package/lib/index.js +161 -68
- package/package.json +15 -3
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.0.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
|
|
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,66 @@ 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.0.0` is required because subsetting reads the module graph, and
|
|
127
|
+
`moduleGraph.getUsedExports()` was exposed to the JS API in rspack 2.0.0.
|
|
128
|
+
|
|
129
|
+
On rspack `2.0.x` there is one limitation: `moduleGraph.getProvidedExports()` only landed in 2.1.0,
|
|
130
|
+
and it is what lets the plugin subset icons reached through a **namespace import**
|
|
131
|
+
(`import * as Icons from '@fluentui/react-icons/fonts/…'`). Because those icons cannot be
|
|
132
|
+
identified, _every_ font in the affected package is left un-subset — not just the namespace import's
|
|
133
|
+
own module — since subsetting from the package's remaining imports would drop glyphs the namespace
|
|
134
|
+
import actually uses. A build warning names the package when this happens. Named imports — the
|
|
135
|
+
common case — are unaffected and subset fully. Upgrade to rspack `>=2.1.0` for complete coverage.
|
|
136
|
+
|
|
137
|
+
## Options
|
|
138
|
+
|
|
139
|
+
### `onDuplicateInstances`
|
|
140
|
+
|
|
141
|
+
`'warn' | 'error'`, default `'warn'`.
|
|
142
|
+
|
|
143
|
+
The plugin subsets against one resolved `@fluentui/react-icons` package instance. When font modules
|
|
144
|
+
resolve from more than one installed copy — peer-dependency variants in a virtual store will do this
|
|
145
|
+
without any version conflict — emitted font assets cannot be attributed safely to one coherent source.
|
|
146
|
+
|
|
147
|
+
The plugin detects multiple participating copies before inspecting font-asset ownership, leaves all
|
|
148
|
+
fonts un-subset so every glyph still renders, and warns with the paths involved. Set `'error'` to fail
|
|
149
|
+
the build instead:
|
|
150
|
+
|
|
151
|
+
```js
|
|
152
|
+
new FluentUIReactIconsFontSubsettingPlugin({ onDuplicateInstances: 'error' });
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
To get subsetting back, collapse the copies onto one instance with bundler `resolve.alias` entries.
|
|
156
|
+
Note that this also binds every copy to a single React and Griffel instance.
|
|
157
|
+
|
|
158
|
+
Using ESM `import` and CommonJS `require()` from the same installation does not count as two copies.
|
|
159
|
+
Their used exports are combined, and each emitted font asset is subset once.
|
|
@@ -0,0 +1,88 @@
|
|
|
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
|
+
/** Optional: exposed to rspack's JS API only in 2.1.0, so absent on the supported 2.0.x 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
|
+
/** webpack's `RuntimeSpec` is `string | SortableSet<string> | undefined`; rspack's is a `Set<string>`. */
|
|
40
|
+
export interface BundlerChunk {
|
|
41
|
+
runtime?: string | ReadonlySet<string>;
|
|
42
|
+
}
|
|
43
|
+
export interface BundlerCompilation {
|
|
44
|
+
hooks: {
|
|
45
|
+
processAssets: {
|
|
46
|
+
tapPromise(options: {
|
|
47
|
+
name: string;
|
|
48
|
+
stage: number;
|
|
49
|
+
}, fn: () => Promise<void>): void;
|
|
50
|
+
};
|
|
51
|
+
};
|
|
52
|
+
modules: Iterable<BundlerModule>;
|
|
53
|
+
chunks: Iterable<BundlerChunk>;
|
|
54
|
+
moduleGraph: BundlerModuleGraph;
|
|
55
|
+
entrypoints: ReadonlyMap<string, unknown>;
|
|
56
|
+
warnings: Error[];
|
|
57
|
+
errors: Error[];
|
|
58
|
+
getAsset(name: string): BundlerAsset | undefined | void;
|
|
59
|
+
getAssets(): readonly BundlerAsset[];
|
|
60
|
+
/**
|
|
61
|
+
* `any` is load-bearing: both bundlers accept a full `webpack-sources` `Source` here, and only
|
|
62
|
+
* `any` is assignable to that, which is what keeps real compilers assignable to this interface.
|
|
63
|
+
* The value passed is always one the bundler itself constructed via `sources.RawSource`.
|
|
64
|
+
*/
|
|
65
|
+
updateAsset(name: string, source: any): void;
|
|
66
|
+
}
|
|
67
|
+
export interface BundlerCompiler {
|
|
68
|
+
context: string;
|
|
69
|
+
/** rspack aliases this to its own namespace, which is why no bundler is imported at runtime. */
|
|
70
|
+
webpack: {
|
|
71
|
+
Compilation: {
|
|
72
|
+
PROCESS_ASSETS_STAGE_OPTIMIZE: number;
|
|
73
|
+
};
|
|
74
|
+
sources: {
|
|
75
|
+
RawSource: new (value: string | Buffer, ...rest: any[]) => BundlerSource;
|
|
76
|
+
};
|
|
77
|
+
};
|
|
78
|
+
hooks: {
|
|
79
|
+
compilation: {
|
|
80
|
+
tap(name: string, fn: (compilation: BundlerCompilation) => void): void;
|
|
81
|
+
};
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/** The shape both bundlers require of a plugin instance. */
|
|
85
|
+
export interface BundlerPlugin {
|
|
86
|
+
apply(compiler: BundlerCompiler): void;
|
|
87
|
+
}
|
|
88
|
+
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,32 @@
|
|
|
1
|
-
import
|
|
2
|
-
export
|
|
1
|
+
import type { BundlerCompiler, BundlerPlugin } from './bundler-api';
|
|
2
|
+
export type * from './bundler-api';
|
|
3
|
+
export interface FluentUIReactIconsFontSubsettingPluginOptions {
|
|
3
4
|
/**
|
|
4
|
-
*
|
|
5
|
+
* What to do when font modules resolve from more than one installed copy of `@fluentui/react-icons`.
|
|
5
6
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
|
|
7
|
+
* `'warn'` (default) leaves all fonts un-subset, so every glyph still renders.
|
|
8
|
+
* `'error'` fails the build instead.
|
|
9
|
+
*/
|
|
10
|
+
onDuplicateInstances?: 'warn' | 'error';
|
|
11
|
+
}
|
|
12
|
+
export default class FluentUIReactIconsFontSubsettingPlugin implements BundlerPlugin {
|
|
13
|
+
private readonly __onDuplicateInstances;
|
|
14
|
+
constructor(options?: FluentUIReactIconsFontSubsettingPluginOptions);
|
|
15
|
+
/**
|
|
16
|
+
* Entry point for the bundler plugin that registers hooks to perform font subsetting for `@fluentui/react-icons`.
|
|
17
|
+
*
|
|
18
|
+
* This method is executed **once** by the bundler when the plugin is initialized during the compiler's
|
|
19
|
+
* bootstrap phase. The internal logic hooked into `processAssets` is executed **once per compilation**
|
|
20
|
+
* (whenever the bundler processes the module graph and prepares to output assets) during the
|
|
9
21
|
* asset optimization stage.
|
|
10
22
|
*
|
|
11
23
|
* It analyzes the module graph to determine which specific icons are used from Fluent UI icon packages
|
|
12
24
|
* and triggers font subsetting to remove unused glyphs from the final output assets.
|
|
13
25
|
*
|
|
14
|
-
*
|
|
26
|
+
* Works with both webpack 5 and rspack. All bundler internals are reached through `compiler.webpack`,
|
|
27
|
+
* which rspack aliases to its own namespace, so neither bundler is imported at runtime.
|
|
28
|
+
*
|
|
29
|
+
* @param compiler - The webpack or rspack compiler instance.
|
|
15
30
|
*/
|
|
16
|
-
apply(compiler:
|
|
31
|
+
apply(compiler: BundlerCompiler): void;
|
|
17
32
|
}
|
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");
|
|
@@ -38,6 +14,8 @@ const FONT_FILES_BASE_NAMES = [
|
|
|
38
14
|
'FluentSystemIcons-Light',
|
|
39
15
|
];
|
|
40
16
|
const FONT_EXTENSIONS = ['.ttf', '.woff', '.woff2'];
|
|
17
|
+
/** Separates "this module's icons are unknowable" from the benign "this module contributes nothing". */
|
|
18
|
+
const UNRESOLVABLE_NAMESPACE_IMPORT = Symbol('unresolvable-namespace-import');
|
|
41
19
|
/**
|
|
42
20
|
* Match both chunk files and atomic font imports, for the standard (Griffel)
|
|
43
21
|
* and headless APIs:
|
|
@@ -48,42 +26,103 @@ const FONT_EXTENSIONS = ['.ttf', '.woff', '.woff2'];
|
|
|
48
26
|
*/
|
|
49
27
|
const REACT_ICONS_FONT_MODULE_IMPORT_PATTERN = /react-icons[\/\\]lib(-cjs)?[\/\\](fonts[\/\\](sizedIcons|icons)[\/\\]chunk-\d+|atoms[\/\\](headless-)?fonts[\/\\][\w-]+)\.c?js$/;
|
|
50
28
|
class FluentUIReactIconsFontSubsettingPlugin {
|
|
29
|
+
constructor(options = {}) {
|
|
30
|
+
this.__onDuplicateInstances = options.onDuplicateInstances ?? 'warn';
|
|
31
|
+
}
|
|
51
32
|
/**
|
|
52
|
-
* Entry point for the
|
|
33
|
+
* Entry point for the bundler plugin that registers hooks to perform font subsetting for `@fluentui/react-icons`.
|
|
53
34
|
*
|
|
54
|
-
* This method is executed **once** by
|
|
55
|
-
* bootstrap phase. The internal logic hooked into `
|
|
56
|
-
* (whenever
|
|
35
|
+
* This method is executed **once** by the bundler when the plugin is initialized during the compiler's
|
|
36
|
+
* bootstrap phase. The internal logic hooked into `processAssets` is executed **once per compilation**
|
|
37
|
+
* (whenever the bundler processes the module graph and prepares to output assets) during the
|
|
57
38
|
* asset optimization stage.
|
|
58
39
|
*
|
|
59
40
|
* It analyzes the module graph to determine which specific icons are used from Fluent UI icon packages
|
|
60
41
|
* and triggers font subsetting to remove unused glyphs from the final output assets.
|
|
61
42
|
*
|
|
62
|
-
*
|
|
43
|
+
* Works with both webpack 5 and rspack. All bundler internals are reached through `compiler.webpack`,
|
|
44
|
+
* which rspack aliases to its own namespace, so neither bundler is imported at runtime.
|
|
45
|
+
*
|
|
46
|
+
* @param compiler - The webpack or rspack compiler instance.
|
|
63
47
|
*/
|
|
64
48
|
apply(compiler) {
|
|
49
|
+
const { Compilation, sources } = compiler.webpack;
|
|
65
50
|
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
|
|
66
|
-
compilation.hooks.
|
|
67
|
-
|
|
68
|
-
const
|
|
51
|
+
compilation.hooks.processAssets.tapPromise({ name: PLUGIN_NAME, stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE }, async () => {
|
|
52
|
+
const runtime = getRuntimeSpec(compiler, compilation);
|
|
53
|
+
const packageUsages = new Map();
|
|
69
54
|
for (const m of compilation.modules) {
|
|
70
55
|
if (isFluentUIReactFontChunk(m)) {
|
|
71
|
-
const icons = resolveUsedIconExports(m, compilation.moduleGraph);
|
|
56
|
+
const icons = resolveUsedIconExports(m, compilation.moduleGraph, runtime);
|
|
72
57
|
if (icons === null) {
|
|
73
58
|
continue;
|
|
74
59
|
}
|
|
75
|
-
const
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
|
|
60
|
+
const outputRoot = (0, path_1.resolve)((0, path_1.dirname)(m.resource), '../..');
|
|
61
|
+
const packageRoot = (0, path_1.dirname)(outputRoot);
|
|
62
|
+
const usage = packageUsages.get(packageRoot) ?? {
|
|
63
|
+
outputRoots: new Set(),
|
|
64
|
+
usedExports: new Set(),
|
|
65
|
+
hasUnresolvableNamespace: false,
|
|
66
|
+
};
|
|
67
|
+
usage.outputRoots.add(outputRoot);
|
|
68
|
+
if (icons === UNRESOLVABLE_NAMESPACE_IMPORT) {
|
|
69
|
+
usage.hasUnresolvableNamespace = true;
|
|
79
70
|
}
|
|
80
|
-
|
|
71
|
+
else {
|
|
72
|
+
for (const icon of icons) {
|
|
73
|
+
usage.usedExports.add(icon);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
packageUsages.set(packageRoot, usage);
|
|
81
77
|
}
|
|
82
78
|
}
|
|
83
79
|
const optimizationPromises = [];
|
|
84
|
-
for (const [
|
|
85
|
-
|
|
86
|
-
|
|
80
|
+
for (const [packageRoot, usage] of packageUsages) {
|
|
81
|
+
if (!usage.hasUnresolvableNamespace) {
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
compilation.warnings.push(new Error(`${PLUGIN_NAME}: "${packageRoot}" is reached through a namespace import (\`import * as ...\`) ` +
|
|
85
|
+
`whose icons cannot be determined — either the bundler does not expose ` +
|
|
86
|
+
`\`moduleGraph.getProvidedExports()\` (rspack <2.1.0), or \`optimization.providedExports\` is ` +
|
|
87
|
+
`disabled. Every font in this package was left un-subset, because subsetting from the ` +
|
|
88
|
+
`remaining imports alone would drop glyphs that are actually used. Named imports are ` +
|
|
89
|
+
`unaffected. Upgrade to rspack >=2.1.0 for full coverage.`));
|
|
90
|
+
}
|
|
91
|
+
if (packageUsages.size > 1) {
|
|
92
|
+
const message = new Error(`${PLUGIN_NAME}: font modules from more than one installed copy of "@fluentui/react-icons" were resolved, ` +
|
|
93
|
+
`so font assets cannot be attributed safely. Fonts were left un-subset to avoid dropping ` +
|
|
94
|
+
`glyphs. Participating copies: ${[...packageUsages.keys()].map((p) => `"${p}"`).join(', ')}. ` +
|
|
95
|
+
`Collapse them onto one instance with ` +
|
|
96
|
+
`bundler \`resolve.alias\` entries — note that this also binds every copy to a single React ` +
|
|
97
|
+
`and Griffel instance.`);
|
|
98
|
+
if (this.__onDuplicateInstances === 'error') {
|
|
99
|
+
compilation.errors.push(message);
|
|
100
|
+
}
|
|
101
|
+
else {
|
|
102
|
+
compilation.warnings.push(message);
|
|
103
|
+
}
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
for (const [packageRoot, usage] of packageUsages) {
|
|
107
|
+
if (usage.hasUnresolvableNamespace) {
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
const fontAssetsByName = new Map();
|
|
111
|
+
for (const outputRoot of usage.outputRoots) {
|
|
112
|
+
const fontAssets = await getFontAssetsAndCodepoints(outputRoot, compilation, compiler.context);
|
|
113
|
+
for (const fontAsset of fontAssets) {
|
|
114
|
+
fontAssetsByName.set(fontAsset.assetName, fontAsset);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (fontAssetsByName.size === 0) {
|
|
118
|
+
// Loud failure: silently shipping an un-subset font is worse than a broken build.
|
|
119
|
+
compilation.warnings.push(new Error(`${PLUGIN_NAME}: found used icon fonts in "${packageRoot}" but could not map any font module ` +
|
|
120
|
+
`to an emitted asset. Fonts will NOT be subset. Ensure a \`type: 'asset'\` ` +
|
|
121
|
+
`(or 'asset/resource') module rule matches /\\.(ttf|woff2?)$/.`));
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
for (const { assetName, codepoints: codepointMap } of fontAssetsByName.values()) {
|
|
125
|
+
optimizationPromises.push(optimizeFontAsset(codepointMap, usage.usedExports, compilation, assetName, sources.RawSource));
|
|
87
126
|
}
|
|
88
127
|
}
|
|
89
128
|
// IMPORTANT: actually await all subsetting work
|
|
@@ -93,7 +132,38 @@ class FluentUIReactIconsFontSubsettingPlugin {
|
|
|
93
132
|
}
|
|
94
133
|
}
|
|
95
134
|
exports.default = FluentUIReactIconsFontSubsettingPlugin;
|
|
96
|
-
|
|
135
|
+
/**
|
|
136
|
+
* Resolves the runtime to query used-exports information for.
|
|
137
|
+
*
|
|
138
|
+
* webpack accepts `undefined`, meaning "merged across all runtimes". rspack requires explicit
|
|
139
|
+
* runtime names, and those are the names of the *runtime chunks* — which are only the entrypoint
|
|
140
|
+
* names by coincidence. Any build that names its runtime chunk (`entry.runtime`,
|
|
141
|
+
* `optimization.runtimeChunk`) makes the two diverge, and querying the wrong runtime reports every
|
|
142
|
+
* module as unused, so nothing gets subset. The runtimes are therefore read off the chunks.
|
|
143
|
+
*/
|
|
144
|
+
function getRuntimeSpec(compiler, compilation) {
|
|
145
|
+
if (!isRspack(compiler)) {
|
|
146
|
+
return undefined;
|
|
147
|
+
}
|
|
148
|
+
const runtimes = new Set();
|
|
149
|
+
for (const chunk of compilation.chunks) {
|
|
150
|
+
const { runtime } = chunk;
|
|
151
|
+
if (typeof runtime === 'string') {
|
|
152
|
+
runtimes.add(runtime);
|
|
153
|
+
}
|
|
154
|
+
else if (runtime) {
|
|
155
|
+
for (const name of runtime) {
|
|
156
|
+
runtimes.add(name);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
// Entrypoint names remain a last resort for the (unexpected) case of chunks without runtimes.
|
|
161
|
+
return runtimes.size > 0 ? Array.from(runtimes) : Array.from(compilation.entrypoints.keys());
|
|
162
|
+
}
|
|
163
|
+
function isRspack(compiler) {
|
|
164
|
+
return 'rspack' in compiler;
|
|
165
|
+
}
|
|
166
|
+
async function optimizeFontAsset(codepointMap, usedExports, compilation, assetName, RawSource) {
|
|
97
167
|
// Build subset text from the used exports set (usually small) instead of scanning all glyphs
|
|
98
168
|
let subsetText = '';
|
|
99
169
|
for (const glyphName of usedExports) {
|
|
@@ -102,13 +172,18 @@ async function optimizeFontAsset(codepointMap, usedExports, compilation, assetNa
|
|
|
102
172
|
subsetText += String.fromCodePoint(codepoint);
|
|
103
173
|
}
|
|
104
174
|
}
|
|
105
|
-
|
|
175
|
+
const asset = compilation.getAsset(assetName);
|
|
176
|
+
if (!asset) {
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
let source = asset.source.source();
|
|
106
180
|
if (typeof source === 'string') {
|
|
107
181
|
source = Buffer.from(source);
|
|
108
182
|
}
|
|
109
|
-
compilation.assets
|
|
183
|
+
// rspack's `compilation.assets` is a read-only proxy, so writes must go through `updateAsset`.
|
|
184
|
+
compilation.updateAsset(assetName, new RawSource(await (0, subset_font_1.default)(source, subsetText, {
|
|
110
185
|
targetFormat: getTargetFormat(assetName),
|
|
111
|
-
}));
|
|
186
|
+
})));
|
|
112
187
|
}
|
|
113
188
|
function getTargetFormat(assetName) {
|
|
114
189
|
switch ((0, path_1.extname)(assetName)) {
|
|
@@ -123,14 +198,14 @@ function getTargetFormat(assetName) {
|
|
|
123
198
|
/**
|
|
124
199
|
* Resolves the set of icon export names that are actually consumed from a font chunk module.
|
|
125
200
|
*
|
|
126
|
-
* Uses
|
|
201
|
+
* Uses the bundler's `moduleGraph.getUsedExports()` which returns one of four shapes:
|
|
127
202
|
*
|
|
128
|
-
* | Return value
|
|
129
|
-
* |
|
|
130
|
-
* | `null`
|
|
131
|
-
* | `false`
|
|
132
|
-
* | `true`
|
|
133
|
-
* | `Set<string
|
|
203
|
+
* | Return value | Meaning | Action |
|
|
204
|
+
* | ------------------------ | ------------------------------------------------------------------ | ------------------------------------------ |
|
|
205
|
+
* | `null` | `optimization.usedExports` is disabled — no usage info available | Skip (cannot determine which glyphs to keep)|
|
|
206
|
+
* | `false` | Module has zero consumers — nothing is imported from it | Skip (nothing to subset) |
|
|
207
|
+
* | `true` | All exports are consumed (e.g. `import * as ns from '...'`) | Fall back to `getProvidedExports()` ¹ |
|
|
208
|
+
* | `Set<string>`/`string[]` | Exact set of named exports that are consumed | Use directly for subsetting |
|
|
134
209
|
*
|
|
135
210
|
* ¹ When all exports are marked as used we can still subset: `getProvidedExports()` tells us
|
|
136
211
|
* which exports this specific module **declares** (not the entire font), so we subset the font
|
|
@@ -142,10 +217,12 @@ function getTargetFormat(assetName) {
|
|
|
142
217
|
* with namespace imports. Without this, namespace imports would skip subsetting entirely and ship
|
|
143
218
|
* the full unsubsetted font.
|
|
144
219
|
*
|
|
145
|
-
* Returns `null` when
|
|
220
|
+
* Returns `null` when the module contributes no glyphs, and {@link UNRESOLVABLE_NAMESPACE_IMPORT}
|
|
221
|
+
* when its glyphs exist but cannot be identified — the caller must then leave the whole package's
|
|
222
|
+
* fonts alone, since dropping the module silently would subset those glyphs away.
|
|
146
223
|
*/
|
|
147
|
-
function resolveUsedIconExports(m, moduleGraph) {
|
|
148
|
-
const usedModuleExports = moduleGraph.getUsedExports(m,
|
|
224
|
+
function resolveUsedIconExports(m, moduleGraph, runtime) {
|
|
225
|
+
const usedModuleExports = moduleGraph.getUsedExports(m, runtime);
|
|
149
226
|
if (usedModuleExports === null) {
|
|
150
227
|
// No info on used exports (optimization.usedExports is disabled) - subsetting requires knowing exactly which exports are used.
|
|
151
228
|
return null;
|
|
@@ -158,18 +235,26 @@ function resolveUsedIconExports(m, moduleGraph) {
|
|
|
158
235
|
// All exports are used (e.g. `import * as ns from '...'` or similar namespace import).
|
|
159
236
|
// Retrieve statically-provided exports from the module graph so we can subset to exactly
|
|
160
237
|
// the glyphs this module declares (rather than the full font or nothing).
|
|
238
|
+
if (typeof moduleGraph.getProvidedExports !== 'function') {
|
|
239
|
+
// rspack <2.1 has no such API; the glyphs are real but unknowable, so the caller must bail.
|
|
240
|
+
return UNRESOLVABLE_NAMESPACE_IMPORT;
|
|
241
|
+
}
|
|
161
242
|
const providedExports = moduleGraph.getProvidedExports(m);
|
|
162
|
-
if (providedExports === null || providedExports ===
|
|
163
|
-
// Provided exports not statically known (optimization.providedExports disabled)
|
|
164
|
-
return
|
|
243
|
+
if (providedExports === null || typeof providedExports === 'boolean') {
|
|
244
|
+
// Provided exports not statically known (optimization.providedExports disabled).
|
|
245
|
+
return UNRESOLVABLE_NAMESPACE_IMPORT;
|
|
165
246
|
}
|
|
166
|
-
return providedExports;
|
|
247
|
+
return [...providedExports];
|
|
167
248
|
}
|
|
168
|
-
// usedModuleExports is a Set<string> with the exact named exports that are used.
|
|
249
|
+
// usedModuleExports is a Set<string> (webpack) or string[] (rspack) with the exact named exports that are used.
|
|
169
250
|
return Array.from(usedModuleExports);
|
|
170
251
|
}
|
|
252
|
+
/**
|
|
253
|
+
* rspack modules are proxies over Rust objects and are never instances of webpack's `NormalModule`,
|
|
254
|
+
* so presence of `resource` is used as the portable discriminator.
|
|
255
|
+
*/
|
|
171
256
|
function isNormalModule(m) {
|
|
172
|
-
return m
|
|
257
|
+
return typeof m.resource === 'string';
|
|
173
258
|
}
|
|
174
259
|
function isFluentUIReactFontChunk(m) {
|
|
175
260
|
if (!isNormalModule(m)) {
|
|
@@ -185,7 +270,13 @@ function isFluentUIReactFontChunk(m) {
|
|
|
185
270
|
}
|
|
186
271
|
return REACT_ICONS_FONT_MODULE_IMPORT_PATTERN.test(resource);
|
|
187
272
|
}
|
|
188
|
-
|
|
273
|
+
/**
|
|
274
|
+
* Maps emitted font assets back to their codepoint tables.
|
|
275
|
+
*
|
|
276
|
+
* Assets are matched through `AssetInfo.sourceFilename` (the originating file, relative to the compiler
|
|
277
|
+
* context) rather than the module's `buildInfo`, which rspack leaves empty for asset modules.
|
|
278
|
+
*/
|
|
279
|
+
async function getFontAssetsAndCodepoints(pkgLibPath, compilation, context) {
|
|
189
280
|
const utilsFontsFolder = (0, path_1.resolve)(pkgLibPath, 'utils/fonts');
|
|
190
281
|
const codepoints = Object.fromEntries(await Promise.all(FONT_FILES_BASE_NAMES.map(async (fontBaseName) => [
|
|
191
282
|
fontBaseName,
|
|
@@ -193,12 +284,14 @@ async function getFontAssetsAndCodepoints(pkgLibPath, compilation) {
|
|
|
193
284
|
])));
|
|
194
285
|
const fontPaths = new Map(FONT_FILES_BASE_NAMES.flatMap((fontBaseName) => FONT_EXTENSIONS.map((ext) => [(0, path_1.resolve)(utilsFontsFolder, `${fontBaseName}${ext}`), codepoints[fontBaseName]])));
|
|
195
286
|
const result = [];
|
|
196
|
-
for (const
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
287
|
+
for (const { name: assetName, info } of compilation.getAssets()) {
|
|
288
|
+
const sourceFilename = info?.sourceFilename;
|
|
289
|
+
if (!sourceFilename) {
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
const codepointsForAsset = fontPaths.get((0, path_1.resolve)(context, sourceFilename));
|
|
293
|
+
if (codepointsForAsset) {
|
|
294
|
+
result.push({ assetName, codepoints: codepointsForAsset });
|
|
202
295
|
}
|
|
203
296
|
}
|
|
204
297
|
return result;
|
package/package.json
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fluentui/react-icons-font-subsetting-webpack-plugin",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.340",
|
|
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
|
|
7
|
+
"test": "yarn run -T vitest run && 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
|
-
"lint": "yarn run -T eslint package.json"
|
|
13
|
+
"lint": "yarn run -T eslint src package.json"
|
|
11
14
|
},
|
|
12
15
|
"engines": {
|
|
13
16
|
"node": ">=14.5.0"
|
|
@@ -30,8 +33,17 @@
|
|
|
30
33
|
"subset-font": "^1.4.0"
|
|
31
34
|
},
|
|
32
35
|
"peerDependencies": {
|
|
36
|
+
"@rspack/core": ">=2.0.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
|
]
|