-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
with-module-federation.ts
329 lines (291 loc) · 8.63 KB
/
with-module-federation.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import {
getNpmPackageSharedConfig,
SharedLibraryConfig,
sharePackages,
shareWorkspaceLibraries,
} from './mfe-webpack';
import {
createProjectGraphAsync,
ProjectGraph,
readCachedProjectGraph,
workspaceRoot,
Workspaces,
} from '@nrwl/devkit';
import {
getRootTsConfigPath,
readTsConfig,
} from '@nrwl/workspace/src/utilities/typescript';
import { ParsedCommandLine } from 'typescript';
import { readWorkspaceJson } from 'nx/src/project-graph/file-utils';
import { readRootPackageJson } from './utils';
import { extname, join } from 'path';
import ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');
export type MFERemotes = string[] | [remoteName: string, remoteUrl: string][];
type SharedFunction = (
libraryName: string,
sharedConfig: SharedLibraryConfig
) => SharedLibraryConfig | false;
type AdditionalSharedConfig = Array<
| string
| [libraryName: string, sharedConfig: SharedLibraryConfig]
| { libraryName: string; sharedConfig: SharedLibraryConfig }
>;
export interface MFEConfig {
name: string;
remotes?: MFERemotes;
exposes?: Record<string, string>;
shared?: SharedFunction;
additionalShared?: AdditionalSharedConfig;
}
function collectDependencies(
projectGraph: ProjectGraph,
name: string,
dependencies = {
workspaceLibraries: new Set<string>(),
npmPackages: new Set<string>(),
},
seen: Set<string> = new Set()
): {
workspaceLibraries: Set<string>;
npmPackages: Set<string>;
} {
if (seen.has(name)) {
return dependencies;
}
seen.add(name);
(projectGraph.dependencies[name] ?? []).forEach((dependency) => {
if (dependency.target.startsWith('npm:')) {
dependencies.npmPackages.add(dependency.target.replace('npm:', ''));
} else {
dependencies.workspaceLibraries.add(dependency.target);
collectDependencies(projectGraph, dependency.target, dependencies, seen);
}
});
return dependencies;
}
function mapWorkspaceLibrariesToTsConfigImport(workspaceLibraries: string[]) {
const { projects } = new Workspaces(
workspaceRoot
).readWorkspaceConfiguration();
const tsConfigPath = process.env.NX_TSCONFIG_PATH ?? getRootTsConfigPath();
const tsConfig: ParsedCommandLine = readTsConfig(tsConfigPath);
const tsconfigPathAliases: Record<string, string[]> = tsConfig.options?.paths;
if (!tsconfigPathAliases) {
return workspaceLibraries;
}
const mappedLibraries = [];
for (const lib of workspaceLibraries) {
const sourceRoot = projects[lib].sourceRoot;
let found = false;
for (const [key, value] of Object.entries(tsconfigPathAliases)) {
if (value.find((p) => p.startsWith(sourceRoot))) {
mappedLibraries.push(key);
found = true;
break;
}
}
if (!found) {
mappedLibraries.push(lib);
}
}
return mappedLibraries;
}
async function getDependentPackagesForProject(
projectGraph: ProjectGraph,
name: string
) {
const { npmPackages, workspaceLibraries } = collectDependencies(
projectGraph,
name
);
return {
workspaceLibraries: mapWorkspaceLibrariesToTsConfigImport([
...workspaceLibraries,
]),
npmPackages: [...npmPackages],
};
}
function determineRemoteUrl(remote: string) {
const workspace = readWorkspaceJson();
let publicHost = '';
try {
publicHost = workspace.projects[remote].targets.serve.options.publicHost;
} catch (error) {
throw new Error(
`Cannot automatically determine URL of remote (${remote}). Looked for property "publicHost" in the project's "serve" target.\n
You can also use the tuple syntax in your webpack config to configure your remotes. e.g. \`remotes: [['remote1', 'http://localhost:4201']]\``
);
}
return `${
publicHost.endsWith('/') ? publicHost.slice(0, -1) : publicHost
}/remoteEntry.mjs`;
}
function mapRemotes(remotes: MFERemotes) {
const mappedRemotes = {};
for (const remote of remotes) {
if (Array.isArray(remote)) {
const [remoteName, remoteLocation] = remote;
const remoteLocationExt = extname(remoteLocation);
mappedRemotes[remoteName] = ['.js', '.mjs'].includes(remoteLocationExt)
? remoteLocation
: join(remoteLocation, 'remoteEntry.mjs');
} else if (typeof remote === 'string') {
mappedRemotes[remote] = determineRemoteUrl(remote);
}
}
return mappedRemotes;
}
function applySharedFunction(
sharedConfig: Record<string, SharedLibraryConfig>,
sharedFn: SharedFunction | undefined
): void {
if (!sharedFn) {
return;
}
for (const [libraryName, library] of Object.entries(sharedConfig)) {
const mappedDependency = sharedFn(libraryName, library);
if (mappedDependency === false) {
delete sharedConfig[libraryName];
continue;
} else if (!mappedDependency) {
continue;
}
sharedConfig[libraryName] = mappedDependency;
}
}
function addStringDependencyToSharedConfig(
sharedConfig: Record<string, SharedLibraryConfig>,
dependency: string,
projectGraph: ProjectGraph
): void {
if (projectGraph.nodes[dependency]) {
sharedConfig[dependency] = { requiredVersion: false };
} else if (projectGraph.externalNodes?.[dependency]) {
const pkgJson = readRootPackageJson();
const config = getNpmPackageSharedConfig(
dependency,
pkgJson.dependencies?.[dependency] ??
pkgJson.devDependencies?.[dependency]
);
if (!config) {
return;
}
sharedConfig[dependency] = config;
} else {
throw new Error(
`The specified dependency "${dependency}" in the additionalShared configuration does not exist in the project graph. ` +
`Please check your additionalShared configuration and make sure you are including valid workspace projects or npm packages.`
);
}
}
function applyAdditionalShared(
sharedConfig: Record<string, SharedLibraryConfig>,
additionalShared: AdditionalSharedConfig | undefined,
projectGraph: ProjectGraph
): void {
if (!additionalShared) {
return;
}
for (const shared of additionalShared) {
if (typeof shared === 'string') {
addStringDependencyToSharedConfig(sharedConfig, shared, projectGraph);
} else if (Array.isArray(shared)) {
sharedConfig[shared[0]] = shared[1];
} else if (typeof shared === 'object') {
sharedConfig[shared.libraryName] = shared.sharedConfig;
}
}
}
function applyDefaultEagerPackages(
sharedConfig: Record<string, SharedLibraryConfig>
) {
const DEFAULT_PACKAGES_TO_LOAD_EAGERLY = ['@angular/localize/init'];
for (const pkg of DEFAULT_PACKAGES_TO_LOAD_EAGERLY) {
if (sharedConfig[pkg]) {
return {
...sharedConfig,
eager: true,
};
}
}
}
export async function withModuleFederation(options: MFEConfig) {
const DEFAULT_NPM_PACKAGES_TO_AVOID = ['zone.js', '@nrwl/angular/mfe'];
let projectGraph: ProjectGraph<any>;
try {
projectGraph = readCachedProjectGraph();
} catch (e) {
projectGraph = await createProjectGraphAsync();
}
const dependencies = await getDependentPackagesForProject(
projectGraph,
options.name
);
const sharedLibraries = shareWorkspaceLibraries(
dependencies.workspaceLibraries
);
const npmPackages = sharePackages(
dependencies.npmPackages.filter(
(pkg) => !DEFAULT_NPM_PACKAGES_TO_AVOID.includes(pkg)
)
);
DEFAULT_NPM_PACKAGES_TO_AVOID.forEach((pkgName) => {
if (pkgName in npmPackages) {
delete npmPackages[pkgName];
}
});
const sharedDependencies = {
...sharedLibraries.getLibraries(),
...npmPackages,
};
applyDefaultEagerPackages(sharedDependencies);
applySharedFunction(sharedDependencies, options.shared);
applyAdditionalShared(
sharedDependencies,
options.additionalShared,
projectGraph
);
const mappedRemotes =
!options.remotes || options.remotes.length === 0
? {}
: mapRemotes(options.remotes);
return (config) => ({
...(config ?? {}),
output: {
...(config.output ?? {}),
uniqueName: options.name,
publicPath: 'auto',
},
optimization: {
...(config.optimization ?? {}),
runtimeChunk: false,
},
resolve: {
...(config.resolve ?? {}),
alias: {
...(config.resolve?.alias ?? {}),
...sharedLibraries.getAliases(),
},
},
experiments: {
...(config.experiments ?? {}),
outputModule: true,
},
plugins: [
...(config.plugins ?? []),
new ModuleFederationPlugin({
name: options.name,
filename: 'remoteEntry.mjs',
exposes: options.exposes,
remotes: mappedRemotes,
shared: {
...sharedDependencies,
},
library: {
type: 'module',
},
}),
sharedLibraries.getReplacementPlugin(),
],
});
}