-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
mfe-webpack.ts
191 lines (172 loc) · 5.46 KB
/
mfe-webpack.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
import {
joinPathFragments,
logger,
readJsonFile,
workspaceRoot,
} from '@nrwl/devkit';
import {
getRootTsConfigPath,
readTsConfig,
} from '@nrwl/workspace/src/utilities/typescript';
import { existsSync, lstatSync, readdirSync } from 'fs';
import { dirname, join, normalize, relative } from 'path';
import { ParsedCommandLine } from 'typescript';
import { NormalModuleReplacementPlugin } from 'webpack';
import { readRootPackageJson } from './utils';
export interface SharedLibraryConfig {
singleton?: boolean;
strictVersion?: boolean;
requiredVersion?: false | string;
eager?: boolean;
}
export function shareWorkspaceLibraries(
libraries: string[],
tsConfigPath = process.env.NX_TSCONFIG_PATH ?? getRootTsConfigPath()
) {
if (!existsSync(tsConfigPath)) {
throw new Error(
`NX MFE: TsConfig Path for workspace libraries does not exist! (${tsConfigPath})`
);
}
const tsConfig: ParsedCommandLine = readTsConfig(tsConfigPath);
const tsconfigPathAliases = tsConfig.options?.paths;
if (!tsconfigPathAliases) {
return {
getAliases: () => [],
getLibraries: () => ({}),
getReplacementPlugin: () =>
new NormalModuleReplacementPlugin(/./, () => {}),
};
}
const pathMappings: { name: string; path: string }[] = [];
for (const [key, paths] of Object.entries(tsconfigPathAliases)) {
if (libraries && libraries.includes(key)) {
const pathToLib = normalize(join(workspaceRoot, paths[0]));
pathMappings.push({
name: key,
path: pathToLib,
});
}
}
return {
getAliases: () =>
pathMappings.reduce(
(aliases, library) => ({ ...aliases, [library.name]: library.path }),
{}
),
getLibraries: (eager?: boolean): Record<string, SharedLibraryConfig> =>
pathMappings.reduce(
(libraries, library) => ({
...libraries,
[library.name]: { requiredVersion: false, eager },
}),
{} as Record<string, SharedLibraryConfig>
),
getReplacementPlugin: () =>
new NormalModuleReplacementPlugin(/./, (req) => {
if (!req.request.startsWith('.')) {
return;
}
const from = req.context;
const to = normalize(join(req.context, req.request));
for (const library of pathMappings) {
const libFolder = normalize(dirname(library.path));
if (!from.startsWith(libFolder) && to.startsWith(libFolder)) {
req.request = library.name;
}
}
}),
};
}
function getNonNodeModulesSubDirs(directory: string): string[] {
return readdirSync(directory)
.filter((file) => file !== 'node_modules')
.map((file) => join(directory, file))
.filter((file) => lstatSync(file).isDirectory());
}
function recursivelyCollectSecondaryEntryPointsFromDirectory(
pkgName: string,
pkgVersion: string,
pkgRoot: string,
directories: string[],
collectedPackages: { name: string; version: string }[]
): void {
for (const directory of directories) {
const packageJsonPath = join(directory, 'package.json');
if (existsSync(packageJsonPath)) {
const importName = joinPathFragments(
pkgName,
relative(pkgRoot, directory)
);
try {
// require the secondary entry point to try to rule out sample code
require.resolve(importName, { paths: [workspaceRoot] });
const { name } = readJsonFile(packageJsonPath);
// further check to make sure what we were able to require is the
// same as the package name
if (name === importName) {
collectedPackages.push({ name, version: pkgVersion });
}
} catch {}
}
const subDirs = getNonNodeModulesSubDirs(directory);
recursivelyCollectSecondaryEntryPointsFromDirectory(
pkgName,
pkgVersion,
pkgRoot,
subDirs,
collectedPackages
);
}
}
function collectPackageSecondaryEntryPoints(
pkgName: string,
pkgVersion: string,
collectedPackages: { name: string; version: string }[]
): void {
const packageJsonPath = require.resolve(`${pkgName}/package.json`, {
paths: [workspaceRoot],
});
const pathToPackage = dirname(packageJsonPath);
const subDirs = getNonNodeModulesSubDirs(pathToPackage);
recursivelyCollectSecondaryEntryPointsFromDirectory(
pkgName,
pkgVersion,
pathToPackage,
subDirs,
collectedPackages
);
}
export function getNpmPackageSharedConfig(
pkgName: string,
version: string
): SharedLibraryConfig | undefined {
if (!version) {
logger.warn(
`Could not find a version for "${pkgName}" in the root "package.json" ` +
'when collecting shared packages for the Module Federation setup. ' +
'The package will not be shared.'
);
return undefined;
}
return { singleton: true, strictVersion: true, requiredVersion: version };
}
export function sharePackages(
packages: string[]
): Record<string, SharedLibraryConfig> {
const pkgJson = readRootPackageJson();
const allPackages: { name: string; version: string }[] = [];
packages.forEach((pkg) => {
const pkgVersion =
pkgJson.dependencies?.[pkg] ?? pkgJson.devDependencies?.[pkg];
allPackages.push({ name: pkg, version: pkgVersion });
collectPackageSecondaryEntryPoints(pkg, pkgVersion, allPackages);
});
return allPackages.reduce((shared, pkg) => {
const config = getNpmPackageSharedConfig(pkg.name, pkg.version);
if (config) {
shared[pkg.name] = config;
}
return shared;
}, {} as Record<string, SharedLibraryConfig>);
}