@angular-architects/native-federation 18.2.0 → 18.2.2

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.
Files changed (104) hide show
  1. package/config.js +5 -0
  2. package/config.js.map +1 -0
  3. package/package.json +4 -3
  4. package/src/builders/build/builder.d.ts +5 -0
  5. package/src/builders/build/builder.js +255 -0
  6. package/src/builders/build/builder.js.map +1 -0
  7. package/src/config.d.ts +2 -0
  8. package/src/config.js +10 -0
  9. package/src/config.js.map +1 -0
  10. package/src/executors/build/executor.d.ts +4 -0
  11. package/src/executors/build/executor.js +13 -0
  12. package/src/executors/build/executor.js.map +1 -0
  13. package/src/generators/native-federation/generator.d.ts +3 -0
  14. package/src/generators/native-federation/generator.js +44 -0
  15. package/src/generators/native-federation/generator.js.map +1 -0
  16. package/src/index.js +1 -0
  17. package/src/index.js.map +1 -0
  18. package/src/patch-angular-build.d.ts +1 -0
  19. package/src/patch-angular-build.js +7 -0
  20. package/src/patch-angular-build.js.map +1 -0
  21. package/src/plugin/dev-externals-mixin.d.ts +1 -0
  22. package/src/plugin/dev-externals-mixin.js +30 -0
  23. package/src/plugin/dev-externals-mixin.js.map +1 -0
  24. package/src/plugin/externals-skip-list.d.ts +2 -0
  25. package/src/plugin/externals-skip-list.js +9 -0
  26. package/src/plugin/externals-skip-list.js.map +1 -0
  27. package/src/plugin/index.d.ts +2 -0
  28. package/src/plugin/index.js +107 -0
  29. package/src/plugin/index.js.map +1 -0
  30. package/src/schematics/appbuilder/schematic.d.ts +4 -0
  31. package/src/schematics/appbuilder/schematic.js +95 -0
  32. package/src/schematics/appbuilder/schematic.js.map +1 -0
  33. package/src/schematics/init/schematic.d.ts +6 -0
  34. package/src/schematics/init/schematic.js +316 -0
  35. package/src/schematics/init/schematic.js.map +1 -0
  36. package/src/schematics/remove/schematic.d.ts +4 -0
  37. package/src/schematics/remove/schematic.js +119 -0
  38. package/src/schematics/remove/schematic.js.map +1 -0
  39. package/src/schematics/update18/schematic.d.ts +2 -0
  40. package/src/schematics/update18/schematic.js +14 -0
  41. package/src/schematics/update18/schematic.js.map +1 -0
  42. package/src/utils/angular-esbuild-adapter.d.ts +9 -0
  43. package/src/utils/angular-esbuild-adapter.js +274 -0
  44. package/src/utils/angular-esbuild-adapter.js.map +1 -0
  45. package/src/utils/create-compiler-options.d.ts +4 -0
  46. package/src/utils/create-compiler-options.js +45 -0
  47. package/src/utils/create-compiler-options.js.map +1 -0
  48. package/src/utils/dev-server.d.ts +7 -0
  49. package/src/utils/dev-server.js +94 -0
  50. package/src/utils/dev-server.js.map +1 -0
  51. package/src/utils/event-sorce.d.ts +9 -0
  52. package/src/utils/event-sorce.js +20 -0
  53. package/src/utils/event-sorce.js.map +1 -0
  54. package/src/utils/mem-resuts.d.ts +29 -0
  55. package/src/utils/mem-resuts.js +58 -0
  56. package/src/utils/mem-resuts.js.map +1 -0
  57. package/src/utils/patch-angular-build.d.ts +3 -0
  58. package/src/utils/patch-angular-build.js +36 -0
  59. package/src/utils/patch-angular-build.js.map +1 -0
  60. package/src/utils/rebuild-events.d.ts +7 -0
  61. package/src/utils/rebuild-events.js +11 -0
  62. package/src/utils/rebuild-events.js.map +1 -0
  63. package/src/utils/shared-mappings-plugin.d.ts +3 -0
  64. package/src/utils/shared-mappings-plugin.js +31 -0
  65. package/src/utils/shared-mappings-plugin.js.map +1 -0
  66. package/src/utils/updateIndexHtml.d.ts +4 -0
  67. package/src/utils/updateIndexHtml.js +34 -0
  68. package/src/utils/updateIndexHtml.js.map +1 -0
  69. package/.eslintrc.json +0 -25
  70. package/docs/migrate.md +0 -173
  71. package/docs/share-faq.md +0 -57
  72. package/docs/update18.md +0 -19
  73. package/example.png +0 -0
  74. package/jest.config.ts +0 -11
  75. package/post-build.js +0 -10
  76. package/project.json +0 -80
  77. package/src/builders/build/builder.ts +0 -370
  78. package/src/config.ts +0 -6
  79. package/src/executors/build/executor.spec.ts +0 -11
  80. package/src/executors/build/executor.ts +0 -12
  81. package/src/generators/native-federation/generator.spec.ts +0 -20
  82. package/src/generators/native-federation/generator.ts +0 -76
  83. package/src/patch-angular-build.ts +0 -8
  84. package/src/plugin/dev-externals-mixin.ts +0 -34
  85. package/src/plugin/externals-skip-list.ts +0 -5
  86. package/src/plugin/index.ts +0 -123
  87. package/src/schematics/appbuilder/schematic.ts +0 -148
  88. package/src/schematics/init/schematic.ts +0 -463
  89. package/src/schematics/remove/schematic.ts +0 -179
  90. package/src/schematics/update18/schematic.ts +0 -10
  91. package/src/utils/angular-esbuild-adapter.ts +0 -438
  92. package/src/utils/create-compiler-options.ts +0 -68
  93. package/src/utils/dev-server.ts +0 -117
  94. package/src/utils/event-sorce.ts +0 -18
  95. package/src/utils/mem-resuts.ts +0 -67
  96. package/src/utils/patch-angular-build.ts +0 -47
  97. package/src/utils/rebuild-events.ts +0 -9
  98. package/src/utils/shared-mappings-plugin.ts +0 -35
  99. package/src/utils/updateIndexHtml.ts +0 -55
  100. package/tsconfig.json +0 -23
  101. package/tsconfig.lib.json +0 -11
  102. package/tsconfig.spec.json +0 -15
  103. /package/{config.ts → config.d.ts} +0 -0
  104. /package/src/{index.ts → index.d.ts} +0 -0
@@ -1,370 +0,0 @@
1
- import * as path from 'path';
2
- import * as fs from 'fs';
3
- import * as mrmime from 'mrmime';
4
-
5
- import { buildApplication, ApplicationBuilderOptions } from '@angular/build';
6
- import {
7
- serveWithVite,
8
- buildApplicationInternal,
9
- } from '@angular/build/private';
10
-
11
- import {
12
- BuilderContext,
13
- BuilderOutput,
14
- createBuilder,
15
- } from '@angular-devkit/architect';
16
-
17
- import { DevServerBuilderOptions } from '@angular-devkit/build-angular';
18
- import { normalizeOptions } from '@angular-devkit/build-angular/src/builders/dev-server/options';
19
-
20
- import { setLogLevel, logger } from '@softarc/native-federation/build';
21
-
22
- import { FederationOptions } from '@softarc/native-federation/build';
23
- import { setBuildAdapter } from '@softarc/native-federation/build';
24
- import {
25
- createAngularBuildAdapter,
26
- setMemResultHandler,
27
- } from '../../utils/angular-esbuild-adapter';
28
- import { getExternals } from '@softarc/native-federation/build';
29
- import { loadFederationConfig } from '@softarc/native-federation/build';
30
- import { buildForFederation } from '@softarc/native-federation/build';
31
- import { targetFromTargetString } from '@angular-devkit/architect';
32
-
33
- import { NfBuilderSchema } from './schema';
34
- import {
35
- reloadBrowser,
36
- reloadShell,
37
- setError,
38
- startServer,
39
- } from '../../utils/dev-server';
40
- import { RebuildHubs } from '../../utils/rebuild-events';
41
- import { updateIndexHtml, updateScriptTags } from '../../utils/updateIndexHtml';
42
- import { existsSync, mkdirSync, rmSync } from 'fs';
43
- import {
44
- EsBuildResult,
45
- MemResults,
46
- NgCliAssetResult,
47
- } from '../../utils/mem-resuts';
48
- import { JsonObject } from '@angular-devkit/core';
49
- import { createSharedMappingsPlugin } from '../../utils/shared-mappings-plugin';
50
- // import { NextHandleFunction } from 'vite';
51
- import { PluginBuild } from 'esbuild';
52
- import { FederationInfo } from '@softarc/native-federation-runtime';
53
-
54
- function _buildApplication(options, context, pluginsOrExtensions) {
55
- let extensions;
56
- if (pluginsOrExtensions && Array.isArray(pluginsOrExtensions)) {
57
- extensions = {
58
- codePlugins: pluginsOrExtensions,
59
- };
60
- } else {
61
- extensions = pluginsOrExtensions;
62
- }
63
- return buildApplicationInternal(
64
- options,
65
- context,
66
- extensions
67
- );
68
- }
69
-
70
- export async function* runBuilder(
71
- nfOptions: NfBuilderSchema,
72
- context: BuilderContext
73
- ): AsyncIterable<BuilderOutput> {
74
- let target = targetFromTargetString(nfOptions.target);
75
-
76
- let _options = (await context.getTargetOptions(
77
- target
78
- )) as unknown as JsonObject & ApplicationBuilderOptions;
79
-
80
- let builder = await context.getBuilderNameForTarget(target);
81
-
82
- if (builder === '@angular-devkit/build-angular:browser-esbuild') {
83
- logger.info('.: NATIVE FEDERATION - UPDATE NEEDED :.');
84
- logger.info('');
85
- logger.info("Since version 17.1, Native Federation uses Angular's");
86
- logger.info('Application-Builder and its Dev-Server.');
87
- logger.info('');
88
- logger.info('If you are sill on Angular 17.0.x, please update to');
89
- logger.info('Angular 17.1.x or downgrade to Native Federation 17.0.x.');
90
- logger.info('');
91
- logger.info('For working with Native Federation 17.1.x (recommented), ');
92
- logger.info('please update your project config, e.g. in angular.json');
93
- logger.info('');
94
- logger.info('This command performs the needed update for default configs:');
95
- logger.info('');
96
- logger.info('\tng g @angular-architects/native-federation:appbuilder');
97
- logger.info('');
98
- logger.info('You need to run it once per application to migrate');
99
- logger.info('Please find more information here: https://shorturl.at/gADJW');
100
- return;
101
- }
102
-
103
- let options = (await context.validateOptions(
104
- _options,
105
- builder
106
- )) as JsonObject & ApplicationBuilderOptions;
107
-
108
- const outerOptions = options as DevServerBuilderOptions;
109
- const normOuterOptions = nfOptions.dev
110
- ? await normalizeOptions(context, context.target.project, outerOptions)
111
- : null;
112
-
113
- if (nfOptions.dev) {
114
- target = targetFromTargetString(outerOptions.buildTarget);
115
- _options = (await context.getTargetOptions(
116
- target
117
- )) as unknown as JsonObject & ApplicationBuilderOptions;
118
-
119
- builder = await context.getBuilderNameForTarget(target);
120
- options = (await context.validateOptions(_options, builder)) as JsonObject &
121
- ApplicationBuilderOptions;
122
- }
123
-
124
- const runServer = !!nfOptions.port;
125
- const write = !runServer;
126
- const watch = !!runServer || nfOptions.watch;
127
-
128
- options.watch = watch;
129
-
130
- if (nfOptions.baseHref) {
131
- options.baseHref = nfOptions.baseHref;
132
- }
133
-
134
- const rebuildEvents = new RebuildHubs();
135
-
136
- const adapter = createAngularBuildAdapter(options, context, rebuildEvents);
137
- setBuildAdapter(adapter);
138
-
139
- setLogLevel(options.verbose ? 'verbose' : 'info');
140
-
141
- const outputPath = options.outputPath;
142
-
143
- const outputOptions: Required<
144
- Exclude<ApplicationBuilderOptions['outputPath'], string>
145
- > = {
146
- browser: 'browser',
147
- server: 'server',
148
- media: 'media',
149
- ...(typeof outputPath === 'string' ? undefined : outputPath),
150
- base: typeof outputPath === 'string' ? outputPath : outputPath.base,
151
- };
152
-
153
- const browserOutputPath = path.join(
154
- outputOptions.base,
155
- outputOptions.browser
156
- );
157
-
158
- const fedOptions: FederationOptions = {
159
- workspaceRoot: context.workspaceRoot,
160
- outputPath: browserOutputPath,
161
- federationConfig: infereConfigPath(options.tsConfig),
162
- tsConfig: options.tsConfig,
163
- verbose: options.verbose,
164
- watch: false, // options.watch,
165
- dev: !!nfOptions.dev,
166
- };
167
-
168
- const config = await loadFederationConfig(fedOptions);
169
- const externals = getExternals(config);
170
- const plugins = [
171
- createSharedMappingsPlugin(config.sharedMappings),
172
- {
173
- name: 'externals',
174
- setup(build: PluginBuild) {
175
- if (build.initialOptions.platform !== 'node') {
176
- build.initialOptions.external = externals.filter(
177
- (e) => e !== 'tslib'
178
- );
179
- }
180
- },
181
- },
182
- ];
183
-
184
- const middleware = [
185
- (req, res, next) => {
186
- const url = removeBaseHref(req, options.baseHref);
187
-
188
- const fileName = path.join(
189
- fedOptions.workspaceRoot,
190
- fedOptions.outputPath,
191
- url
192
- );
193
-
194
- const exists = fs.existsSync(fileName);
195
-
196
- if (url !== '/' && url !== '' && exists) {
197
- const lookup = mrmime.lookup;
198
- const mimeType = lookup(path.extname(fileName)) || 'text/javascript';
199
- const rawBody = fs.readFileSync(fileName, 'utf-8');
200
- const body = addDebugInformation(url, rawBody);
201
- res.writeHead(200, {
202
- 'Content-Type': mimeType,
203
- 'Access-Control-Allow-Origin': '*',
204
- 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
205
- 'Access-Control-Allow-Headers': 'Content-Type',
206
- });
207
- res.end(body);
208
- } else {
209
- next();
210
- }
211
- },
212
- ];
213
-
214
- const memResults = new MemResults();
215
-
216
- let first = true;
217
- let lastResult: { success: boolean } | undefined;
218
-
219
- if (existsSync(fedOptions.outputPath)) {
220
- rmSync(fedOptions.outputPath, { recursive: true });
221
- }
222
-
223
- if (!existsSync(fedOptions.outputPath)) {
224
- mkdirSync(fedOptions.outputPath, { recursive: true });
225
- }
226
-
227
- if (!write) {
228
- setMemResultHandler((outFiles, outDir) => {
229
- const fullOutDir = outDir
230
- ? path.join(fedOptions.workspaceRoot, outDir)
231
- : null;
232
- memResults.add(outFiles.map((f) => new EsBuildResult(f, fullOutDir)));
233
- });
234
- }
235
-
236
- try {
237
- await buildForFederation(config, fedOptions, externals);
238
- } catch (e) {
239
- process.exit(1);
240
- }
241
-
242
- options.deleteOutputPath = false;
243
-
244
- // TODO: Clarify how DevServer needs to be executed. Not sure if its right.
245
- // TODO: Clarify if buildApplication is needed `executeDevServerBuilder` seems to choose the correct DevServer
246
-
247
- const appBuilderName = '@angular-devkit/build-angular:application';
248
-
249
- const builderRun = nfOptions.dev
250
- ? serveWithVite(
251
- normOuterOptions,
252
- appBuilderName,
253
- _buildApplication,
254
- context,
255
- nfOptions.skipHtmlTransform
256
- ? {}
257
- : { indexHtml: transformIndexHtml(nfOptions) },
258
- {
259
- buildPlugins: plugins,
260
- middleware,
261
- }
262
- )
263
- : buildApplication(options, context, plugins);
264
-
265
- // builderRun.output.subscribe(async (output) => {
266
- for await (const output of builderRun) {
267
- lastResult = output;
268
-
269
- if (!output.success) {
270
- setError('Compilation Error');
271
- reloadBrowser();
272
- continue;
273
- } else {
274
- setError(null);
275
- }
276
-
277
- if (!write && output.outputFiles) {
278
- memResults.add(output.outputFiles.map((file) => new EsBuildResult(file)));
279
- }
280
-
281
- if (!write && output.assetFiles) {
282
- memResults.add(
283
- output.assetFiles.map((file) => new NgCliAssetResult(file))
284
- );
285
- }
286
-
287
- if (write && !nfOptions.dev && !nfOptions.skipHtmlTransform) {
288
- updateIndexHtml(fedOptions, nfOptions);
289
- }
290
-
291
- // if (first && runServer) {
292
- // startServer(nfOptions, fedOptions.outputPath, memResults);
293
- // }
294
-
295
- // if (!first && runServer) {
296
- // reloadBrowser();
297
- // }
298
-
299
- if (!runServer) {
300
- yield output;
301
- }
302
-
303
- if (!first && nfOptions.dev) {
304
- setTimeout(async () => {
305
- // logger.info('Rebuilding federation artefacts ...');
306
- // await Promise.all([rebuildEvents.rebuild.emit()]);
307
- await buildForFederation(config, fedOptions, externals);
308
- logger.info('Done!');
309
-
310
- if (runServer) {
311
- setTimeout(() => reloadShell(nfOptions.shell), 0);
312
- }
313
- }, nfOptions.rebuildDelay);
314
- }
315
-
316
- first = false;
317
- }
318
-
319
- yield lastResult || { success: false };
320
- }
321
-
322
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
323
- export default createBuilder(runBuilder) as any;
324
-
325
- function removeBaseHref(req: any, baseHref?: string) {
326
- let url = req.url;
327
-
328
- if (baseHref && url.startsWith(baseHref)) {
329
- url = url.substr(baseHref.length);
330
- }
331
- return url;
332
- }
333
-
334
- function infereConfigPath(tsConfig: string): string {
335
- const relProjectPath = path.dirname(tsConfig);
336
- const relConfigPath = path.join(relProjectPath, 'federation.config.js');
337
-
338
- return relConfigPath;
339
- }
340
-
341
- function transformIndexHtml(
342
- nfOptions: NfBuilderSchema
343
- ): (content: string) => Promise<string> {
344
- return (content: string): Promise<string> =>
345
- Promise.resolve(
346
- updateScriptTags(content, 'main.js', 'polyfills.js', nfOptions)
347
- );
348
- }
349
-
350
- function addDebugInformation(fileName: string, rawBody: string): string {
351
- if (fileName !== '/remoteEntry.json') {
352
- return rawBody;
353
- }
354
-
355
- const remoteEntry = JSON.parse(rawBody) as FederationInfo;
356
- const shared = remoteEntry.shared;
357
-
358
- if (!shared) {
359
- return rawBody;
360
- }
361
-
362
- const sharedForVite = shared.map((s) => ({
363
- ...s,
364
- packageName: `/@id/${s.packageName}`,
365
- }));
366
-
367
- remoteEntry.shared = [...shared, ...sharedForVite];
368
-
369
- return JSON.stringify(remoteEntry, null, 2);
370
- }
package/src/config.ts DELETED
@@ -1,6 +0,0 @@
1
- export { withNativeFederation } from '@softarc/native-federation/build';
2
- export {
3
- findRootTsConfigJson,
4
- share,
5
- shareAll,
6
- } from '@softarc/native-federation/build';
@@ -1,11 +0,0 @@
1
- import { BuildExecutorSchema } from './schema';
2
- import executor from './executor';
3
-
4
- const options: BuildExecutorSchema = {};
5
-
6
- describe('Build Executor', () => {
7
- it('can run', async () => {
8
- const output = await executor(options, {});
9
- expect(output.success).toBe(true);
10
- });
11
- });
@@ -1,12 +0,0 @@
1
- import { BuildExecutorSchema } from './schema';
2
-
3
- export default async function runExecutor(
4
- options: BuildExecutorSchema,
5
- nowos: unknown
6
- ) {
7
- console.log('Executor ran for Build', options, nowos);
8
-
9
- return {
10
- success: true,
11
- };
12
- }
@@ -1,20 +0,0 @@
1
- import { createTreeWithEmptyWorkspace } from '@nx/devkit/testing';
2
- import { Tree, readProjectConfiguration } from '@nx/devkit';
3
-
4
- import generator from './generator';
5
- import { NativeFederationGeneratorSchema } from './schema';
6
-
7
- describe('native-federation generator', () => {
8
- let appTree: Tree;
9
- const options: NativeFederationGeneratorSchema = { name: 'test' };
10
-
11
- beforeEach(() => {
12
- appTree = createTreeWithEmptyWorkspace();
13
- });
14
-
15
- it('should run successfully', async () => {
16
- await generator(appTree, options);
17
- const config = readProjectConfiguration(appTree, 'test');
18
- expect(config).toBeDefined();
19
- });
20
- });
@@ -1,76 +0,0 @@
1
- import {
2
- addProjectConfiguration,
3
- formatFiles,
4
- generateFiles,
5
- getWorkspaceLayout,
6
- names,
7
- offsetFromRoot,
8
- Tree,
9
- } from '@nx/devkit';
10
- import * as path from 'path';
11
- import { NativeFederationGeneratorSchema } from './schema';
12
-
13
- interface NormalizedSchema extends NativeFederationGeneratorSchema {
14
- projectName: string;
15
- projectRoot: string;
16
- projectDirectory: string;
17
- parsedTags: string[];
18
- }
19
-
20
- function normalizeOptions(
21
- tree: Tree,
22
- options: NativeFederationGeneratorSchema
23
- ): NormalizedSchema {
24
- const name = names(options.name).fileName;
25
- const projectDirectory = options.directory
26
- ? `${names(options.directory).fileName}/${name}`
27
- : name;
28
- const projectName = projectDirectory.replace(new RegExp('/', 'g'), '-');
29
- const projectRoot = `${getWorkspaceLayout(tree).libsDir}/${projectDirectory}`;
30
- const parsedTags = options.tags
31
- ? options.tags.split(',').map((s) => s.trim())
32
- : [];
33
-
34
- return {
35
- ...options,
36
- projectName,
37
- projectRoot,
38
- projectDirectory,
39
- parsedTags,
40
- };
41
- }
42
-
43
- function addFiles(tree: Tree, options: NormalizedSchema) {
44
- const templateOptions = {
45
- ...options,
46
- ...names(options.name),
47
- offsetFromRoot: offsetFromRoot(options.projectRoot),
48
- template: '',
49
- };
50
- generateFiles(
51
- tree,
52
- path.join(__dirname, 'files'),
53
- options.projectRoot,
54
- templateOptions
55
- );
56
- }
57
-
58
- export default async function (
59
- tree: Tree,
60
- options: NativeFederationGeneratorSchema
61
- ) {
62
- const normalizedOptions = normalizeOptions(tree, options);
63
- addProjectConfiguration(tree, normalizedOptions.projectName, {
64
- root: normalizedOptions.projectRoot,
65
- projectType: 'library',
66
- sourceRoot: `${normalizedOptions.projectRoot}/src`,
67
- targets: {
68
- build: {
69
- executor: '@angular-architects/native-federation:build',
70
- },
71
- },
72
- tags: normalizedOptions.parsedTags,
73
- });
74
- addFiles(tree, normalizedOptions);
75
- await formatFiles(tree);
76
- }
@@ -1,8 +0,0 @@
1
- // import { patchAngularBuild } from './utils/patch-angular-build';
2
-
3
- // const workspaceRoot = process.cwd();
4
- // patchAngularBuild(workspaceRoot);
5
-
6
- console.log(
7
- 'Please remove the postbuild task calling patch-angular-build. This is not needed since Native Federation 18.1 anymore!'
8
- );
@@ -1,34 +0,0 @@
1
- import { federationBuilder } from '@softarc/native-federation/build';
2
- import { filterExternals } from './externals-skip-list';
3
-
4
- // see: https://github.com/vitejs/vite/issues/6393#issuecomment-1006819717
5
-
6
- export const devExternalsMixin = {
7
- enforce: 'pre',
8
- config(config) {
9
- config.optimizeDeps = {
10
- ...(config.optimizeDeps ?? {}),
11
- exclude: [
12
- ...(config.optimizeDeps?.exclude ?? []),
13
- ...filterExternals(federationBuilder.externals),
14
- ],
15
- };
16
- },
17
- configResolved(resolvedConfig) {
18
- const VALID_ID_PREFIX = `/@id/`;
19
- const reg = new RegExp(
20
- `${VALID_ID_PREFIX}(${federationBuilder.externals.join('|')})`,
21
- 'g'
22
- );
23
- resolvedConfig.plugins.push({
24
- name: 'vite-plugin-ignore-static-import-replace-idprefix',
25
- transform: (code) =>
26
- reg.test(code) ? code.replace(reg, (m, s1) => s1) : code,
27
- });
28
- },
29
- resolveId: (id) => {
30
- if (filterExternals(federationBuilder.externals).includes(id)) {
31
- return { id, external: true };
32
- }
33
- },
34
- } as any;
@@ -1,5 +0,0 @@
1
- export const externalsSkipList = new Set(['tslib']);
2
-
3
- export function filterExternals(deps: string[]): string[] {
4
- return deps.filter((d) => !externalsSkipList.has(d));
5
- }
@@ -1,123 +0,0 @@
1
- import * as fs from 'fs';
2
- import * as path from 'path';
3
-
4
- import { lookup } from 'mrmime';
5
- import { devExternalsMixin } from './dev-externals-mixin';
6
- import { filterExternals } from './externals-skip-list';
7
- import {
8
- BuildHelperParams,
9
- federationBuilder,
10
- } from '@softarc/native-federation/build';
11
- import { FederationInfo } from '@softarc/native-federation-runtime';
12
-
13
- type FedInfoRef = { federationInfo: FederationInfo };
14
-
15
- export const federation = (params: BuildHelperParams) => {
16
- return {
17
- ...devExternalsMixin,
18
- name: '@module-federation/vite', // required, will show up in warnings and errors
19
- async config(...args) {
20
- await federationBuilder.init(params);
21
- devExternalsMixin.config(...args);
22
- },
23
- options(o: unknown) {
24
- o!['external'] = filterExternals(federationBuilder.externals);
25
- },
26
- async closeBundle() {
27
- await federationBuilder.build();
28
- },
29
- async configureServer(server) {
30
- const fedInfoRef: FedInfoRef = {
31
- federationInfo: federationBuilder.federationInfo,
32
- };
33
- await configureDevServer(server, params, fedInfoRef);
34
- },
35
- transformIndexHtml(html: string) {
36
- const fragment = '<script src="polyfills.js" type="module-shim">';
37
- const updated = `
38
- <script type="esms-options">
39
- {
40
- "shimMode": true
41
- }
42
- </script>
43
- <script src="polyfills.js" type="module">
44
- `;
45
- html = html.replace(/type="module"/g, 'type="module-shim"');
46
- return html.replace(fragment, updated);
47
- },
48
- };
49
- };
50
-
51
- const configureDevServer = async (
52
- server: any,
53
- params: BuildHelperParams,
54
- fedInfo: FedInfoRef
55
- ) => {
56
- await federationBuilder.build();
57
-
58
- const op = params.options;
59
- const dist = path.join(op.workspaceRoot, op.outputPath);
60
- server.middlewares.use(serveFromDist(dist, fedInfo));
61
- };
62
-
63
- const serveFromDist = (dist: string, fedInfoRef: FedInfoRef) => {
64
- const fedFiles = new Set([
65
- ...fedInfoRef.federationInfo.shared.map((s) =>
66
- path.join('/', s.outFileName)
67
- ),
68
- ...fedInfoRef.federationInfo.exposes.map((e) =>
69
- path.join('/', e.outFileName)
70
- ),
71
- '/remoteEntry.json',
72
- ]);
73
-
74
- return (req, res, next) => {
75
- if (!req.url || req.url.endsWith('/index.html') || !fedFiles.has(req.url)) {
76
- next();
77
- return;
78
- }
79
-
80
- const file = path.join(dist, req.url);
81
- if (fs.existsSync(file) && fs.lstatSync(file).isFile()) {
82
- res.setHeader('Access-Control-Allow-Origin', '*');
83
- const type = lookup(req.url) || '';
84
- res.setHeader('Content-Type', type);
85
-
86
- const content = fs.readFileSync(file, 'utf-8');
87
- // const modified = enhanceFile(file, content);
88
- const modified = content;
89
- res.write(modified);
90
- res.end();
91
- return;
92
- }
93
-
94
- next();
95
- };
96
- };
97
-
98
- // TODO: Unused, to delete?
99
- // const enhanceFile = (fileName: string, src: string): string => {
100
- // if (fileName.endsWith('remoteEntry.json')) {
101
- // let remoteEntry = JSON.parse(fs.readFileSync(fileName, 'utf-8'));
102
- // remoteEntry = {
103
- // ...remoteEntry,
104
- // shared: (remoteEntry.shared || []).map((el) => ({
105
- // ...el,
106
- // outFileName: el.dev?.entryPoint.includes('/node_modules/')
107
- // ? el.outFileName
108
- // : normalize(path.join('@fs', el.dev?.entryPoint || '')),
109
- // })),
110
- // exposes: (remoteEntry.exposes || []).map((el) => ({
111
- // ...el,
112
- // outFileName: normalize(path.join('@fs', el.dev?.entryPoint || '')),
113
- // })),
114
- // };
115
- // return JSON.stringify(remoteEntry, null, 2);
116
- // }
117
- // return src;
118
- // };
119
-
120
- // TODO: Unused, to delete?
121
- // const normalize = (path: string): string => {
122
- // return path.replace(/\\/g, '/');
123
- // };