@nx/webpack 16.9.0-beta.0 → 16.9.0-beta.1

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/index.d.ts CHANGED
@@ -13,3 +13,4 @@ export * from './src/executors/webpack/webpack.impl';
13
13
  export * from './src/utils/get-css-module-local-ident';
14
14
  export * from './src/utils/with-nx';
15
15
  export * from './src/utils/with-web';
16
+ export * from './src/utils/module-federation/public-api';
package/index.js CHANGED
@@ -16,3 +16,4 @@ tslib_1.__exportStar(require("./src/executors/webpack/webpack.impl"), exports);
16
16
  tslib_1.__exportStar(require("./src/utils/get-css-module-local-ident"), exports);
17
17
  tslib_1.__exportStar(require("./src/utils/with-nx"), exports);
18
18
  tslib_1.__exportStar(require("./src/utils/with-web"), exports);
19
+ tslib_1.__exportStar(require("./src/utils/module-federation/public-api"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nx/webpack",
3
- "version": "16.9.0-beta.0",
3
+ "version": "16.9.0-beta.1",
4
4
  "private": false,
5
5
  "description": "The Nx Plugin for Webpack contains executors and generators that support building applications using Webpack.",
6
6
  "repository": {
@@ -30,9 +30,9 @@
30
30
  },
31
31
  "dependencies": {
32
32
  "@babel/core": "^7.22.9",
33
- "@nrwl/webpack": "16.9.0-beta.0",
34
- "@nx/devkit": "16.9.0-beta.0",
35
- "@nx/js": "16.9.0-beta.0",
33
+ "@nrwl/webpack": "16.9.0-beta.1",
34
+ "@nx/devkit": "16.9.0-beta.1",
35
+ "@nx/js": "16.9.0-beta.1",
36
36
  "autoprefixer": "^10.4.9",
37
37
  "babel-loader": "^9.1.2",
38
38
  "browserslist": "^4.21.4",
@@ -70,5 +70,5 @@
70
70
  "access": "public"
71
71
  },
72
72
  "type": "commonjs",
73
- "gitHead": "822fb12c3f0bbaeb6d4a6fbc6cb1064a291e907f"
73
+ "gitHead": "5056d6cefb2949ba865019e8b71e633fba28c091"
74
74
  }
@@ -0,0 +1,6 @@
1
+ import type { ProjectGraph } from '@nx/devkit';
2
+ import type { WorkspaceLibrary } from './models';
3
+ export declare function getDependentPackagesForProject(projectGraph: ProjectGraph, name: string): {
4
+ workspaceLibraries: WorkspaceLibrary[];
5
+ npmPackages: string[];
6
+ };
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getDependentPackagesForProject = void 0;
4
+ const typescript_1 = require("./typescript");
5
+ function getDependentPackagesForProject(projectGraph, name) {
6
+ const { npmPackages, workspaceLibraries } = collectDependencies(projectGraph, name);
7
+ return {
8
+ workspaceLibraries: [...workspaceLibraries.values()],
9
+ npmPackages: [...npmPackages],
10
+ };
11
+ }
12
+ exports.getDependentPackagesForProject = getDependentPackagesForProject;
13
+ function collectDependencies(projectGraph, name, dependencies = {
14
+ workspaceLibraries: new Map(),
15
+ npmPackages: new Set(),
16
+ }, seen = new Set()) {
17
+ if (seen.has(name)) {
18
+ return dependencies;
19
+ }
20
+ seen.add(name);
21
+ (projectGraph.dependencies[name] ?? []).forEach((dependency) => {
22
+ if (dependency.target.startsWith('npm:')) {
23
+ dependencies.npmPackages.add(dependency.target.replace('npm:', ''));
24
+ }
25
+ else {
26
+ dependencies.workspaceLibraries.set(dependency.target, {
27
+ name: dependency.target,
28
+ root: projectGraph.nodes[dependency.target].data.root,
29
+ importKey: getLibraryImportPath(dependency.target, projectGraph),
30
+ });
31
+ collectDependencies(projectGraph, dependency.target, dependencies, seen);
32
+ }
33
+ });
34
+ return dependencies;
35
+ }
36
+ function getLibraryImportPath(library, projectGraph) {
37
+ const tsConfigPathMappings = (0, typescript_1.readTsPathMappings)();
38
+ const sourceRoot = projectGraph.nodes[library].data.sourceRoot;
39
+ for (const [key, value] of Object.entries(tsConfigPathMappings)) {
40
+ if (value.find((path) => path.startsWith(sourceRoot))) {
41
+ return key;
42
+ }
43
+ }
44
+ return undefined;
45
+ }
@@ -0,0 +1,5 @@
1
+ export * from './share';
2
+ export * from './dependencies';
3
+ export * from './package-json';
4
+ export * from './remotes';
5
+ export * from './models';
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./share"), exports);
5
+ tslib_1.__exportStar(require("./dependencies"), exports);
6
+ tslib_1.__exportStar(require("./package-json"), exports);
7
+ tslib_1.__exportStar(require("./remotes"), exports);
8
+ tslib_1.__exportStar(require("./models"), exports);
@@ -0,0 +1,39 @@
1
+ import type { NormalModuleReplacementPlugin } from 'webpack';
2
+ export type ModuleFederationLibrary = {
3
+ type: string;
4
+ name: string;
5
+ };
6
+ export type WorkspaceLibrary = {
7
+ name: string;
8
+ root: string;
9
+ importKey: string | undefined;
10
+ };
11
+ export type SharedWorkspaceLibraryConfig = {
12
+ getAliases: () => Record<string, string>;
13
+ getLibraries: (eager?: boolean) => Record<string, SharedLibraryConfig>;
14
+ getReplacementPlugin: () => NormalModuleReplacementPlugin;
15
+ };
16
+ export type Remotes = string[] | [remoteName: string, remoteUrl: string][];
17
+ export interface SharedLibraryConfig {
18
+ singleton?: boolean;
19
+ strictVersion?: boolean;
20
+ requiredVersion?: false | string;
21
+ eager?: boolean;
22
+ }
23
+ export type SharedFunction = (libraryName: string, sharedConfig: SharedLibraryConfig) => undefined | false | SharedLibraryConfig;
24
+ export type AdditionalSharedConfig = Array<string | [libraryName: string, sharedConfig: SharedLibraryConfig] | {
25
+ libraryName: string;
26
+ sharedConfig: SharedLibraryConfig;
27
+ }>;
28
+ export interface ModuleFederationConfig {
29
+ name: string;
30
+ remotes?: Remotes;
31
+ library?: ModuleFederationLibrary;
32
+ exposes?: Record<string, string>;
33
+ shared?: SharedFunction;
34
+ additionalShared?: AdditionalSharedConfig;
35
+ }
36
+ export type WorkspaceLibrarySecondaryEntryPoint = {
37
+ name: string;
38
+ path: string;
39
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,8 @@
1
+ export declare function readRootPackageJson(): {
2
+ dependencies?: {
3
+ [key: string]: string;
4
+ };
5
+ devDependencies?: {
6
+ [key: string]: string;
7
+ };
8
+ };
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readRootPackageJson = void 0;
4
+ const fs_1 = require("fs");
5
+ const devkit_1 = require("@nx/devkit");
6
+ function readRootPackageJson() {
7
+ const pkgJsonPath = (0, devkit_1.joinPathFragments)(devkit_1.workspaceRoot, 'package.json');
8
+ if (!(0, fs_1.existsSync)(pkgJsonPath)) {
9
+ throw new Error('NX MF: Could not find root package.json to determine dependency versions.');
10
+ }
11
+ return (0, devkit_1.readJsonFile)(pkgJsonPath);
12
+ }
13
+ exports.readRootPackageJson = readRootPackageJson;
@@ -0,0 +1,6 @@
1
+ import { AdditionalSharedConfig, ModuleFederationConfig, ModuleFederationLibrary, Remotes, SharedFunction, SharedLibraryConfig, SharedWorkspaceLibraryConfig, WorkspaceLibrary, WorkspaceLibrarySecondaryEntryPoint } from './models';
2
+ import { applyAdditionalShared, applySharedFunction, getNpmPackageSharedConfig, sharePackages, shareWorkspaceLibraries } from './share';
3
+ import { mapRemotes, mapRemotesForSSR } from './remotes';
4
+ import { getDependentPackagesForProject } from './dependencies';
5
+ import { readRootPackageJson } from './package-json';
6
+ export { ModuleFederationConfig, SharedLibraryConfig, SharedWorkspaceLibraryConfig, AdditionalSharedConfig, WorkspaceLibrary, SharedFunction, WorkspaceLibrarySecondaryEntryPoint, Remotes, ModuleFederationLibrary, applySharedFunction, applyAdditionalShared, getNpmPackageSharedConfig, shareWorkspaceLibraries, sharePackages, mapRemotes, mapRemotesForSSR, getDependentPackagesForProject, readRootPackageJson, };
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readRootPackageJson = exports.getDependentPackagesForProject = exports.mapRemotesForSSR = exports.mapRemotes = exports.sharePackages = exports.shareWorkspaceLibraries = exports.getNpmPackageSharedConfig = exports.applyAdditionalShared = exports.applySharedFunction = void 0;
4
+ const share_1 = require("./share");
5
+ Object.defineProperty(exports, "applyAdditionalShared", { enumerable: true, get: function () { return share_1.applyAdditionalShared; } });
6
+ Object.defineProperty(exports, "applySharedFunction", { enumerable: true, get: function () { return share_1.applySharedFunction; } });
7
+ Object.defineProperty(exports, "getNpmPackageSharedConfig", { enumerable: true, get: function () { return share_1.getNpmPackageSharedConfig; } });
8
+ Object.defineProperty(exports, "sharePackages", { enumerable: true, get: function () { return share_1.sharePackages; } });
9
+ Object.defineProperty(exports, "shareWorkspaceLibraries", { enumerable: true, get: function () { return share_1.shareWorkspaceLibraries; } });
10
+ const remotes_1 = require("./remotes");
11
+ Object.defineProperty(exports, "mapRemotes", { enumerable: true, get: function () { return remotes_1.mapRemotes; } });
12
+ Object.defineProperty(exports, "mapRemotesForSSR", { enumerable: true, get: function () { return remotes_1.mapRemotesForSSR; } });
13
+ const dependencies_1 = require("./dependencies");
14
+ Object.defineProperty(exports, "getDependentPackagesForProject", { enumerable: true, get: function () { return dependencies_1.getDependentPackagesForProject; } });
15
+ const package_json_1 = require("./package-json");
16
+ Object.defineProperty(exports, "readRootPackageJson", { enumerable: true, get: function () { return package_json_1.readRootPackageJson; } });
@@ -0,0 +1,19 @@
1
+ import { Remotes } from './models';
2
+ /**
3
+ * Map remote names to a format that can be understood and used by Module
4
+ * Federation.
5
+ *
6
+ * @param remotes - The remotes to map
7
+ * @param remoteEntryExt - The file extension of the remoteEntry file
8
+ * @param determineRemoteUrl - The function used to lookup the URL of the served remote
9
+ */
10
+ export declare function mapRemotes(remotes: Remotes, remoteEntryExt: 'js' | 'mjs', determineRemoteUrl: (remote: string) => string): Record<string, string>;
11
+ /**
12
+ * Map remote names to a format that can be understood and used by Module
13
+ * Federation.
14
+ *
15
+ * @param remotes - The remotes to map
16
+ * @param remoteEntryExt - The file extension of the remoteEntry file
17
+ * @param determineRemoteUrl - The function used to lookup the URL of the served remote
18
+ */
19
+ export declare function mapRemotesForSSR(remotes: Remotes, remoteEntryExt: 'js' | 'mjs', determineRemoteUrl: (remote: string) => string): Record<string, string>;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mapRemotesForSSR = exports.mapRemotes = void 0;
4
+ const path_1 = require("path");
5
+ /**
6
+ * Map remote names to a format that can be understood and used by Module
7
+ * Federation.
8
+ *
9
+ * @param remotes - The remotes to map
10
+ * @param remoteEntryExt - The file extension of the remoteEntry file
11
+ * @param determineRemoteUrl - The function used to lookup the URL of the served remote
12
+ */
13
+ function mapRemotes(remotes, remoteEntryExt, determineRemoteUrl) {
14
+ const mappedRemotes = {};
15
+ for (const remote of remotes) {
16
+ if (Array.isArray(remote)) {
17
+ const [remoteName, remoteLocation] = remote;
18
+ const remoteLocationExt = (0, path_1.extname)(remoteLocation);
19
+ mappedRemotes[remoteName] = ['.js', '.mjs'].includes(remoteLocationExt)
20
+ ? remoteLocation
21
+ : `${remoteLocation.endsWith('/')
22
+ ? remoteLocation.slice(0, -1)
23
+ : remoteLocation}/remoteEntry.${remoteEntryExt}`;
24
+ }
25
+ else if (typeof remote === 'string') {
26
+ mappedRemotes[remote] = determineRemoteUrl(remote);
27
+ }
28
+ }
29
+ return mappedRemotes;
30
+ }
31
+ exports.mapRemotes = mapRemotes;
32
+ /**
33
+ * Map remote names to a format that can be understood and used by Module
34
+ * Federation.
35
+ *
36
+ * @param remotes - The remotes to map
37
+ * @param remoteEntryExt - The file extension of the remoteEntry file
38
+ * @param determineRemoteUrl - The function used to lookup the URL of the served remote
39
+ */
40
+ function mapRemotesForSSR(remotes, remoteEntryExt, determineRemoteUrl) {
41
+ const mappedRemotes = {};
42
+ for (const remote of remotes) {
43
+ if (Array.isArray(remote)) {
44
+ const [remoteName, remoteLocation] = remote;
45
+ const remoteLocationExt = (0, path_1.extname)(remoteLocation);
46
+ mappedRemotes[remoteName] = `${remoteName}@${['.js', '.mjs'].includes(remoteLocationExt)
47
+ ? remoteLocation
48
+ : `${remoteLocation.endsWith('/')
49
+ ? remoteLocation.slice(0, -1)
50
+ : remoteLocation}/remoteEntry.${remoteEntryExt}`}`;
51
+ }
52
+ else if (typeof remote === 'string') {
53
+ mappedRemotes[remote] = `${remote}@${determineRemoteUrl(remote)}`;
54
+ }
55
+ }
56
+ return mappedRemotes;
57
+ }
58
+ exports.mapRemotesForSSR = mapRemotesForSSR;
@@ -0,0 +1,12 @@
1
+ import type { WorkspaceLibrary } from './models';
2
+ import { WorkspaceLibrarySecondaryEntryPoint } from './models';
3
+ export declare function collectWorkspaceLibrarySecondaryEntryPoints(library: WorkspaceLibrary, tsconfigPathAliases: Record<string, string[]>): WorkspaceLibrarySecondaryEntryPoint[];
4
+ export declare function getNonNodeModulesSubDirs(directory: string): string[];
5
+ export declare function recursivelyCollectSecondaryEntryPointsFromDirectory(pkgName: string, pkgVersion: string, pkgRoot: string, mainEntryPointExports: any | undefined, directories: string[], collectedPackages: {
6
+ name: string;
7
+ version: string;
8
+ }[]): void;
9
+ export declare function collectPackageSecondaryEntryPoints(pkgName: string, pkgVersion: string, collectedPackages: {
10
+ name: string;
11
+ version: string;
12
+ }[]): void;
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.collectPackageSecondaryEntryPoints = exports.recursivelyCollectSecondaryEntryPointsFromDirectory = exports.getNonNodeModulesSubDirs = exports.collectWorkspaceLibrarySecondaryEntryPoints = void 0;
4
+ const path_1 = require("path");
5
+ const fs_1 = require("fs");
6
+ const devkit_1 = require("@nx/devkit");
7
+ const nx_1 = require("@nx/devkit/nx");
8
+ let { readModulePackageJson } = (0, nx_1.requireNx)();
9
+ // TODO: Remove this in Nx 18 when Nx 16.7.0 is no longer supported
10
+ readModulePackageJson =
11
+ readModulePackageJson ??
12
+ require('nx/src/utils/package-json').readModulePackageJson;
13
+ function collectWorkspaceLibrarySecondaryEntryPoints(library, tsconfigPathAliases) {
14
+ const libraryRoot = (0, path_1.join)(devkit_1.workspaceRoot, library.root);
15
+ const needsSecondaryEntryPointsCollected = (0, fs_1.existsSync)((0, path_1.join)(libraryRoot, 'ng-package.json'));
16
+ const secondaryEntryPoints = [];
17
+ if (needsSecondaryEntryPointsCollected) {
18
+ const tsConfigAliasesForLibWithSecondaryEntryPoints = Object.entries(tsconfigPathAliases).reduce((acc, [tsKey, tsPaths]) => {
19
+ if (!tsKey.startsWith(library.importKey)) {
20
+ return { ...acc };
21
+ }
22
+ if (tsPaths.some((path) => path.startsWith(`${library.root}/`))) {
23
+ acc = { ...acc, [tsKey]: tsPaths };
24
+ }
25
+ return acc;
26
+ }, {});
27
+ for (const [alias] of Object.entries(tsConfigAliasesForLibWithSecondaryEntryPoints)) {
28
+ const pathToLib = (0, path_1.dirname)((0, path_1.join)(devkit_1.workspaceRoot, tsconfigPathAliases[alias][0]));
29
+ let searchDir = pathToLib;
30
+ while (searchDir !== libraryRoot) {
31
+ if ((0, fs_1.existsSync)((0, path_1.join)(searchDir, 'ng-package.json'))) {
32
+ secondaryEntryPoints.push({ name: alias, path: pathToLib });
33
+ break;
34
+ }
35
+ searchDir = (0, path_1.dirname)(searchDir);
36
+ }
37
+ }
38
+ }
39
+ return secondaryEntryPoints;
40
+ }
41
+ exports.collectWorkspaceLibrarySecondaryEntryPoints = collectWorkspaceLibrarySecondaryEntryPoints;
42
+ function getNonNodeModulesSubDirs(directory) {
43
+ return (0, fs_1.readdirSync)(directory)
44
+ .filter((file) => file !== 'node_modules')
45
+ .map((file) => (0, path_1.join)(directory, file))
46
+ .filter((file) => (0, fs_1.lstatSync)(file).isDirectory());
47
+ }
48
+ exports.getNonNodeModulesSubDirs = getNonNodeModulesSubDirs;
49
+ function recursivelyCollectSecondaryEntryPointsFromDirectory(pkgName, pkgVersion, pkgRoot, mainEntryPointExports, directories, collectedPackages) {
50
+ for (const directory of directories) {
51
+ const packageJsonPath = (0, path_1.join)(directory, 'package.json');
52
+ const relativeEntryPointPath = (0, path_1.relative)(pkgRoot, directory);
53
+ const entryPointName = (0, devkit_1.joinPathFragments)(pkgName, relativeEntryPointPath);
54
+ if ((0, fs_1.existsSync)(packageJsonPath)) {
55
+ try {
56
+ // require the secondary entry point to try to rule out sample code
57
+ require.resolve(entryPointName, { paths: [devkit_1.workspaceRoot] });
58
+ const { name } = (0, devkit_1.readJsonFile)(packageJsonPath);
59
+ // further check to make sure what we were able to require is the
60
+ // same as the package name
61
+ if (name === entryPointName) {
62
+ collectedPackages.push({ name, version: pkgVersion });
63
+ }
64
+ }
65
+ catch { }
66
+ }
67
+ else if (mainEntryPointExports) {
68
+ // if the package.json doesn't exist, check if the directory is
69
+ // exported by the main entry point
70
+ const entryPointExportKey = `./${relativeEntryPointPath}`;
71
+ const entryPointInfo = mainEntryPointExports[entryPointExportKey];
72
+ if (entryPointInfo) {
73
+ collectedPackages.push({
74
+ name: entryPointName,
75
+ version: pkgVersion,
76
+ });
77
+ }
78
+ }
79
+ const subDirs = getNonNodeModulesSubDirs(directory);
80
+ recursivelyCollectSecondaryEntryPointsFromDirectory(pkgName, pkgVersion, pkgRoot, mainEntryPointExports, subDirs, collectedPackages);
81
+ }
82
+ }
83
+ exports.recursivelyCollectSecondaryEntryPointsFromDirectory = recursivelyCollectSecondaryEntryPointsFromDirectory;
84
+ function collectPackageSecondaryEntryPoints(pkgName, pkgVersion, collectedPackages) {
85
+ let pathToPackage;
86
+ let packageJsonPath;
87
+ let packageJson;
88
+ try {
89
+ ({ path: packageJsonPath, packageJson } = readModulePackageJson(pkgName));
90
+ pathToPackage = (0, path_1.dirname)(packageJsonPath);
91
+ }
92
+ catch {
93
+ // the package.json might not resolve if the package has the "exports"
94
+ // entry and is not exporting the package.json file, fall back to trying
95
+ // to find it from the top-level node_modules
96
+ pathToPackage = (0, path_1.join)(devkit_1.workspaceRoot, 'node_modules', pkgName);
97
+ packageJsonPath = (0, path_1.join)(pathToPackage, 'package.json');
98
+ if (!(0, fs_1.existsSync)(packageJsonPath)) {
99
+ // might not exist if it's nested in another package, just return here
100
+ return;
101
+ }
102
+ packageJson = (0, devkit_1.readJsonFile)(packageJsonPath);
103
+ }
104
+ const { exports } = packageJson;
105
+ const subDirs = getNonNodeModulesSubDirs(pathToPackage);
106
+ recursivelyCollectSecondaryEntryPointsFromDirectory(pkgName, pkgVersion, pathToPackage, exports, subDirs, collectedPackages);
107
+ }
108
+ exports.collectPackageSecondaryEntryPoints = collectPackageSecondaryEntryPoints;
@@ -0,0 +1,48 @@
1
+ import type { SharedLibraryConfig, SharedWorkspaceLibraryConfig, WorkspaceLibrary } from './models';
2
+ import { AdditionalSharedConfig, SharedFunction } from './models';
3
+ import { type ProjectGraph } from '@nx/devkit';
4
+ /**
5
+ * Build an object of functions to be used with the ModuleFederationPlugin to
6
+ * share Nx Workspace Libraries between Hosts and Remotes.
7
+ *
8
+ * @param libraries - The Nx Workspace Libraries to share
9
+ * @param tsConfigPath - The path to TS Config File that contains the Path Mappings for the Libraries
10
+ */
11
+ export declare function shareWorkspaceLibraries(libraries: WorkspaceLibrary[], tsConfigPath?: string): SharedWorkspaceLibraryConfig;
12
+ /**
13
+ * Build the Module Federation Share Config for a specific package and the
14
+ * specified version of that package.
15
+ * @param pkgName - Name of the package to share
16
+ * @param version - Version of the package to require by other apps in the Module Federation setup
17
+ */
18
+ export declare function getNpmPackageSharedConfig(pkgName: string, version: string): SharedLibraryConfig | undefined;
19
+ /**
20
+ * Create a dictionary of packages and their Module Federation Shared Config
21
+ * from an array of package names.
22
+ *
23
+ * Lookup the versions of the packages from the root package.json file in the
24
+ * workspace.
25
+ * @param packages - Array of package names as strings
26
+ */
27
+ export declare function sharePackages(packages: string[]): Record<string, SharedLibraryConfig>;
28
+ /**
29
+ * Apply a custom function provided by the user that will modify the Shared Config
30
+ * of the dependencies for the Module Federation build.
31
+ *
32
+ * @param sharedConfig - The original Shared Config to be modified
33
+ * @param sharedFn - The custom function to run
34
+ */
35
+ export declare function applySharedFunction(sharedConfig: Record<string, SharedLibraryConfig>, sharedFn: SharedFunction | undefined): void;
36
+ /**
37
+ * Add additional dependencies to the shared package that may not have been
38
+ * discovered by the project graph.
39
+ *
40
+ * This can be useful for applications that use a Dependency Injection system
41
+ * that expects certain Singleton values to be present in the shared injection
42
+ * hierarchy.
43
+ *
44
+ * @param sharedConfig - The original Shared Config
45
+ * @param additionalShared - The additional dependencies to add
46
+ * @param projectGraph - The Nx project graph
47
+ */
48
+ export declare function applyAdditionalShared(sharedConfig: Record<string, SharedLibraryConfig>, additionalShared: AdditionalSharedConfig | undefined, projectGraph: ProjectGraph): void;
@@ -0,0 +1,183 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.applyAdditionalShared = exports.applySharedFunction = exports.sharePackages = exports.getNpmPackageSharedConfig = exports.shareWorkspaceLibraries = void 0;
4
+ const path_1 = require("path");
5
+ const package_json_1 = require("./package-json");
6
+ const typescript_1 = require("./typescript");
7
+ const secondary_entry_points_1 = require("./secondary-entry-points");
8
+ const devkit_1 = require("@nx/devkit");
9
+ /**
10
+ * Build an object of functions to be used with the ModuleFederationPlugin to
11
+ * share Nx Workspace Libraries between Hosts and Remotes.
12
+ *
13
+ * @param libraries - The Nx Workspace Libraries to share
14
+ * @param tsConfigPath - The path to TS Config File that contains the Path Mappings for the Libraries
15
+ */
16
+ function shareWorkspaceLibraries(libraries, tsConfigPath = process.env.NX_TSCONFIG_PATH ?? (0, typescript_1.getRootTsConfigPath)()) {
17
+ if (!libraries) {
18
+ return getEmptySharedLibrariesConfig();
19
+ }
20
+ const tsconfigPathAliases = (0, typescript_1.readTsPathMappings)(tsConfigPath);
21
+ if (!Object.keys(tsconfigPathAliases).length) {
22
+ return getEmptySharedLibrariesConfig();
23
+ }
24
+ const pathMappings = [];
25
+ for (const [key, paths] of Object.entries(tsconfigPathAliases)) {
26
+ const library = libraries.find((lib) => lib.importKey === key);
27
+ if (!library) {
28
+ continue;
29
+ }
30
+ // This is for Angular Projects that use ng-package.json
31
+ // It will do nothing for React Projects
32
+ (0, secondary_entry_points_1.collectWorkspaceLibrarySecondaryEntryPoints)(library, tsconfigPathAliases).forEach(({ name, path }) => pathMappings.push({
33
+ name,
34
+ path,
35
+ }));
36
+ pathMappings.push({
37
+ name: key,
38
+ path: (0, path_1.normalize)((0, path_1.join)(devkit_1.workspaceRoot, paths[0])),
39
+ });
40
+ }
41
+ const webpack = require('webpack');
42
+ return {
43
+ getAliases: () => pathMappings.reduce((aliases, library) => ({ ...aliases, [library.name]: library.path }), {}),
44
+ getLibraries: (eager) => pathMappings.reduce((libraries, library) => ({
45
+ ...libraries,
46
+ [library.name]: { requiredVersion: false, eager },
47
+ }), {}),
48
+ getReplacementPlugin: () => new webpack.NormalModuleReplacementPlugin(/./, (req) => {
49
+ if (!req.request.startsWith('.')) {
50
+ return;
51
+ }
52
+ const from = req.context;
53
+ const to = (0, path_1.normalize)((0, path_1.join)(req.context, req.request));
54
+ for (const library of pathMappings) {
55
+ const libFolder = (0, path_1.normalize)((0, path_1.dirname)(library.path));
56
+ if (!from.startsWith(libFolder) && to.startsWith(libFolder)) {
57
+ req.request = library.name;
58
+ }
59
+ }
60
+ }),
61
+ };
62
+ }
63
+ exports.shareWorkspaceLibraries = shareWorkspaceLibraries;
64
+ /**
65
+ * Build the Module Federation Share Config for a specific package and the
66
+ * specified version of that package.
67
+ * @param pkgName - Name of the package to share
68
+ * @param version - Version of the package to require by other apps in the Module Federation setup
69
+ */
70
+ function getNpmPackageSharedConfig(pkgName, version) {
71
+ if (!version) {
72
+ devkit_1.logger.warn(`Could not find a version for "${pkgName}" in the root "package.json" ` +
73
+ 'when collecting shared packages for the Module Federation setup. ' +
74
+ 'The package will not be shared.');
75
+ return undefined;
76
+ }
77
+ return { singleton: true, strictVersion: true, requiredVersion: version };
78
+ }
79
+ exports.getNpmPackageSharedConfig = getNpmPackageSharedConfig;
80
+ /**
81
+ * Create a dictionary of packages and their Module Federation Shared Config
82
+ * from an array of package names.
83
+ *
84
+ * Lookup the versions of the packages from the root package.json file in the
85
+ * workspace.
86
+ * @param packages - Array of package names as strings
87
+ */
88
+ function sharePackages(packages) {
89
+ const pkgJson = (0, package_json_1.readRootPackageJson)();
90
+ const allPackages = [];
91
+ packages.forEach((pkg) => {
92
+ const pkgVersion = pkgJson.dependencies?.[pkg] ?? pkgJson.devDependencies?.[pkg];
93
+ allPackages.push({ name: pkg, version: pkgVersion });
94
+ (0, secondary_entry_points_1.collectPackageSecondaryEntryPoints)(pkg, pkgVersion, allPackages);
95
+ });
96
+ return allPackages.reduce((shared, pkg) => {
97
+ const config = getNpmPackageSharedConfig(pkg.name, pkg.version);
98
+ if (config) {
99
+ shared[pkg.name] = config;
100
+ }
101
+ return shared;
102
+ }, {});
103
+ }
104
+ exports.sharePackages = sharePackages;
105
+ /**
106
+ * Apply a custom function provided by the user that will modify the Shared Config
107
+ * of the dependencies for the Module Federation build.
108
+ *
109
+ * @param sharedConfig - The original Shared Config to be modified
110
+ * @param sharedFn - The custom function to run
111
+ */
112
+ function applySharedFunction(sharedConfig, sharedFn) {
113
+ if (!sharedFn) {
114
+ return;
115
+ }
116
+ for (const [libraryName, library] of Object.entries(sharedConfig)) {
117
+ const mappedDependency = sharedFn(libraryName, library);
118
+ if (mappedDependency === false) {
119
+ delete sharedConfig[libraryName];
120
+ continue;
121
+ }
122
+ else if (!mappedDependency) {
123
+ continue;
124
+ }
125
+ sharedConfig[libraryName] = mappedDependency;
126
+ }
127
+ }
128
+ exports.applySharedFunction = applySharedFunction;
129
+ /**
130
+ * Add additional dependencies to the shared package that may not have been
131
+ * discovered by the project graph.
132
+ *
133
+ * This can be useful for applications that use a Dependency Injection system
134
+ * that expects certain Singleton values to be present in the shared injection
135
+ * hierarchy.
136
+ *
137
+ * @param sharedConfig - The original Shared Config
138
+ * @param additionalShared - The additional dependencies to add
139
+ * @param projectGraph - The Nx project graph
140
+ */
141
+ function applyAdditionalShared(sharedConfig, additionalShared, projectGraph) {
142
+ if (!additionalShared) {
143
+ return;
144
+ }
145
+ for (const shared of additionalShared) {
146
+ if (typeof shared === 'string') {
147
+ addStringDependencyToSharedConfig(sharedConfig, shared, projectGraph);
148
+ }
149
+ else if (Array.isArray(shared)) {
150
+ sharedConfig[shared[0]] = shared[1];
151
+ }
152
+ else if (typeof shared === 'object') {
153
+ sharedConfig[shared.libraryName] = shared.sharedConfig;
154
+ }
155
+ }
156
+ }
157
+ exports.applyAdditionalShared = applyAdditionalShared;
158
+ function addStringDependencyToSharedConfig(sharedConfig, dependency, projectGraph) {
159
+ if (projectGraph.nodes[dependency]) {
160
+ sharedConfig[dependency] = { requiredVersion: false };
161
+ }
162
+ else if (projectGraph.externalNodes?.[`npm:${dependency}`]) {
163
+ const pkgJson = (0, package_json_1.readRootPackageJson)();
164
+ const config = getNpmPackageSharedConfig(dependency, pkgJson.dependencies?.[dependency] ??
165
+ pkgJson.devDependencies?.[dependency]);
166
+ if (!config) {
167
+ return;
168
+ }
169
+ sharedConfig[dependency] = config;
170
+ }
171
+ else {
172
+ throw new Error(`The specified dependency "${dependency}" in the additionalShared configuration does not exist in the project graph. ` +
173
+ `Please check your additionalShared configuration and make sure you are including valid workspace projects or npm packages.`);
174
+ }
175
+ }
176
+ function getEmptySharedLibrariesConfig() {
177
+ const webpack = require('webpack');
178
+ return {
179
+ getAliases: () => ({}),
180
+ getLibraries: () => ({}),
181
+ getReplacementPlugin: () => new webpack.NormalModuleReplacementPlugin(/./, () => { }),
182
+ };
183
+ }
@@ -0,0 +1,4 @@
1
+ import { ParsedCommandLine } from 'typescript';
2
+ export declare function readTsPathMappings(tsConfigPath?: string): ParsedCommandLine['options']['paths'];
3
+ export declare function readTsConfig(tsConfigPath: string): ParsedCommandLine;
4
+ export declare function getRootTsConfigPath(): string | null;
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getRootTsConfigPath = exports.readTsConfig = exports.readTsPathMappings = void 0;
4
+ const fs_1 = require("fs");
5
+ const path_1 = require("path");
6
+ const devkit_1 = require("@nx/devkit");
7
+ let tsConfig;
8
+ let tsPathMappings;
9
+ function readTsPathMappings(tsConfigPath = process.env.NX_TSCONFIG_PATH ?? getRootTsConfigPath()) {
10
+ if (tsPathMappings) {
11
+ return tsPathMappings;
12
+ }
13
+ tsConfig ??= readTsConfiguration(tsConfigPath);
14
+ tsPathMappings = {};
15
+ Object.entries(tsConfig.options?.paths ?? {}).forEach(([alias, paths]) => {
16
+ tsPathMappings[alias] = paths.map((path) => path.replace(/^\.\//, ''));
17
+ });
18
+ return tsPathMappings;
19
+ }
20
+ exports.readTsPathMappings = readTsPathMappings;
21
+ function readTsConfiguration(tsConfigPath) {
22
+ if (!(0, fs_1.existsSync)(tsConfigPath)) {
23
+ throw new Error(`NX MF: TsConfig Path for workspace libraries does not exist! (${tsConfigPath}).`);
24
+ }
25
+ return readTsConfig(tsConfigPath);
26
+ }
27
+ let tsModule;
28
+ function readTsConfig(tsConfigPath) {
29
+ if (!tsModule) {
30
+ tsModule = require('typescript');
31
+ }
32
+ const readResult = tsModule.readConfigFile(tsConfigPath, tsModule.sys.readFile);
33
+ return tsModule.parseJsonConfigFileContent(readResult.config, tsModule.sys, (0, path_1.dirname)(tsConfigPath));
34
+ }
35
+ exports.readTsConfig = readTsConfig;
36
+ function getRootTsConfigPath() {
37
+ const tsConfigFileName = getRootTsConfigFileName();
38
+ return tsConfigFileName ? (0, path_1.join)(devkit_1.workspaceRoot, tsConfigFileName) : null;
39
+ }
40
+ exports.getRootTsConfigPath = getRootTsConfigPath;
41
+ function getRootTsConfigFileName() {
42
+ for (const tsConfigName of ['tsconfig.base.json', 'tsconfig.json']) {
43
+ const tsConfigPath = (0, path_1.join)(devkit_1.workspaceRoot, tsConfigName);
44
+ if ((0, fs_1.existsSync)(tsConfigPath)) {
45
+ return tsConfigName;
46
+ }
47
+ }
48
+ return null;
49
+ }