Skip to content

Commit edced6c

Browse files
authored
fix(module-federation): Add migration for ssr server file to run on it's own port (nrwl#27411)
<!-- Please make sure you have read the submission guidelines before posting an PR --> <!-- https://github.com/nrwl/nx/blob/master/CONTRIBUTING.md#-submitting-a-pr --> <!-- Please make sure that your commit message follows our format --> <!-- Example: `fix(nx): must begin with lowercase` --> <!-- If this is a particularly complex change or feature addition, you can request a dedicated Nx release for this pull request branch. Mention someone from the Nx team or the `@nrwl/nx-pipelines-reviewers` and they will confirm if the PR warrants its own release for testing purposes, and generate it for you if appropriate. --> ## Current Behavior <!-- This is the behavior we have today --> Currently, if you have a SSR Mfe project and you run multiple ssr projects using the 'serve' target it would fail due to conflicting ports unless explicitly set `PORT=4202 node dist/acme/server.js`. ## Expected Behavior <!-- This is the behavior we should expect with the changes in this PR --> Now the default is to have the server take the same port as it was generated with so that if you run multiple server apps that depends on other apps in dev mode there will be no conflicts. ## Related Issue(s) <!-- Please link the issue being fixed so it gets closed when this is merged. --> Fixes #
1 parent f4659d7 commit edced6c

File tree

4 files changed

+359
-1
lines changed

4 files changed

+359
-1
lines changed

packages/react/migrations.json

+6
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,12 @@
4747
"version": "19.6.0-beta.4",
4848
"description": "Ensure Module Federation DTS is turned off by default.",
4949
"factory": "./src/migrations/update-19-6-0/turn-off-dts-by-default"
50+
},
51+
"update-module-federation-ssr-server-file": {
52+
"cli": "nx",
53+
"version": "19.6.0-beta.4",
54+
"description": "Update the server file for Module Federation SSR port value to be the same as the 'serve' target port value.",
55+
"factory": "./src/migrations/update-19-6-0/update-ssr-server-port"
5056
}
5157
},
5258
"packageJsonUpdates": {

packages/react/src/generators/setup-ssr/files/server.ts__tmpl__

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ const port = process.env['PORT'] || <%= port %>;
88
const app = express();
99

1010
const browserDist = path.join(process.cwd(), '<%= browserBuildOutputPath %>');
11-
const indexPath =path.join(browserDist, 'index.html');
11+
const indexPath = path.join(browserDist, 'index.html');
1212

1313
app.use(cors());
1414

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,206 @@
1+
import { readProjectConfiguration, type Tree } from '@nx/devkit';
2+
import { createTreeWithEmptyWorkspace } from 'nx/src/devkit-testing-exports';
3+
import hostGenerator from '../../generators/host/host';
4+
import { Linter } from '@nx/eslint';
5+
import updateSsrServerPort from './update-ssr-server-port';
6+
describe('update-19-6-0 update-ssr-server-port migration', () => {
7+
let tree: Tree;
8+
9+
beforeEach(() => {
10+
tree = createTreeWithEmptyWorkspace();
11+
});
12+
13+
it('should update host and remote port server files', async () => {
14+
await hostGenerator(tree, {
15+
name: 'shell',
16+
e2eTestRunner: 'none',
17+
unitTestRunner: 'none',
18+
ssr: true,
19+
linter: Linter.EsLint,
20+
projectNameAndRootFormat: 'as-provided',
21+
style: 'css',
22+
remotes: ['product'],
23+
});
24+
const remotePort = readProjectConfiguration(tree, 'product').targets.serve
25+
.options.port;
26+
27+
const shellPort = readProjectConfiguration(tree, 'shell').targets.serve
28+
.options.port;
29+
30+
// This should already exists in the generated project
31+
tree.write(
32+
'product/server.ts',
33+
tree
34+
.read('product/server.ts', 'utf-8')
35+
.replace(
36+
'const port = 4201;',
37+
`const port = process.env['PORT'] || 4200;`
38+
)
39+
);
40+
41+
updateSsrServerPort(tree);
42+
expect(tree.read('product/server.ts', 'utf-8')).toContain(
43+
`port = process.env['PORT'] || ${remotePort}`
44+
);
45+
expect(tree.read('product/server.ts', 'utf-8')).toMatchInlineSnapshot(`
46+
"import * as path from 'path';
47+
import express from 'express';
48+
import cors from 'cors';
49+
50+
import { handleRequest } from './src/main.server';
51+
52+
const port = process.env['PORT'] || 4201;
53+
const app = express();
54+
55+
const browserDist = path.join(process.cwd(), 'dist/product/browser');
56+
const serverDist = path.join(process.cwd(), 'dist/product/server');
57+
const indexPath = path.join(browserDist, 'index.html');
58+
59+
app.use(cors());
60+
61+
// Client-side static bundles
62+
app.get(
63+
'*.*',
64+
express.static(browserDist, {
65+
maxAge: '1y',
66+
})
67+
);
68+
69+
// Static bundles for server-side module federation
70+
app.use(
71+
'/server',
72+
express.static(serverDist, {
73+
maxAge: '1y',
74+
})
75+
);
76+
77+
app.use('*', handleRequest(indexPath));
78+
79+
const server = app.listen(port, () => {
80+
console.log(\`Express server listening on http://localhost:\${port}\`);
81+
82+
/**
83+
* DO NOT REMOVE IF USING @nx/react:module-federation-dev-ssr executor
84+
* to serve your Host application with this Remote application.
85+
* This message allows Nx to determine when the Remote is ready to be
86+
* consumed by the Host.
87+
*/
88+
process.send?.('nx.server.ready');
89+
});
90+
91+
server.on('error', console.error);
92+
"
93+
`);
94+
95+
tree.write(
96+
'shell/server.ts',
97+
tree
98+
.read('shell/server.ts', 'utf-8')
99+
.replace(
100+
'const port = 4200;',
101+
`const port = process.env['PORT'] || 4200;`
102+
)
103+
);
104+
105+
updateSsrServerPort(tree);
106+
expect(tree.read('shell/server.ts', 'utf-8')).toContain(
107+
`port = process.env.PORT || ${shellPort}`
108+
);
109+
expect(tree.read('shell/server.ts', 'utf-8')).toMatchInlineSnapshot(`
110+
"import * as path from 'path';
111+
import express from 'express';
112+
import cors from 'cors';
113+
import { handleRequest } from './src/main.server';
114+
const port = process.env.PORT || 4200;
115+
const app = express();
116+
const browserDist = path.join(process.cwd(), 'dist/shell/browser');
117+
const indexPath = path.join(browserDist, 'index.html');
118+
app.use(cors());
119+
app.get('*.*', express.static(browserDist, {
120+
maxAge: '1y',
121+
}));
122+
app.use('*', handleRequest(indexPath));
123+
const server = app.listen(port, () => {
124+
console.log(\`Express server listening on http://localhost:\${port}\`);
125+
});
126+
server.on('error', console.error);
127+
"
128+
`);
129+
});
130+
131+
it('should update a host project server file', async () => {
132+
await hostGenerator(tree, {
133+
name: 'host',
134+
e2eTestRunner: 'none',
135+
unitTestRunner: 'none',
136+
ssr: true,
137+
linter: Linter.EsLint,
138+
projectNameAndRootFormat: 'as-provided',
139+
style: 'css',
140+
});
141+
142+
const hostPort = readProjectConfiguration(tree, 'host').targets.serve
143+
.options.port;
144+
145+
tree.write(
146+
'host/server.ts',
147+
tree
148+
.read('host/server.ts', 'utf-8')
149+
.replace(
150+
'const port = 4200;',
151+
`const port = process.env['PORT'] || 4200;`
152+
)
153+
);
154+
155+
updateSsrServerPort(tree);
156+
157+
expect(tree.read('host/server.ts', 'utf-8')).toContain(
158+
`port = process.env.PORT || ${hostPort}`
159+
);
160+
expect(tree.read('host/server.ts', 'utf-8')).toMatchInlineSnapshot(`
161+
"import * as path from 'path';
162+
import express from 'express';
163+
import cors from 'cors';
164+
import { handleRequest } from './src/main.server';
165+
const port = process.env.PORT || 4200;
166+
const app = express();
167+
const browserDist = path.join(process.cwd(), 'dist/host/browser');
168+
const indexPath = path.join(browserDist, 'index.html');
169+
app.use(cors());
170+
app.get('*.*', express.static(browserDist, {
171+
maxAge: '1y',
172+
}));
173+
app.use('*', handleRequest(indexPath));
174+
const server = app.listen(port, () => {
175+
console.log(\`Express server listening on http://localhost:\${port}\`);
176+
});
177+
server.on('error', console.error);
178+
"
179+
`);
180+
});
181+
182+
it('should not update a mfe project that is not ssr', async () => {
183+
await hostGenerator(tree, {
184+
name: 'shell-not-ssr',
185+
e2eTestRunner: 'none',
186+
unitTestRunner: 'none',
187+
ssr: false,
188+
linter: Linter.EsLint,
189+
projectNameAndRootFormat: 'as-provided',
190+
style: 'css',
191+
});
192+
193+
tree.write('shell-not-ssr/server.ts', 'const port = 9999;');
194+
const shellPort = readProjectConfiguration(tree, 'shell-not-ssr').targets
195+
.serve.options.port;
196+
197+
updateSsrServerPort(tree);
198+
199+
expect(tree.read('shell-not-ssr/server.ts', 'utf-8')).not.toContain(
200+
`port = ${shellPort}`
201+
);
202+
expect(tree.read('shell-not-ssr/server.ts', 'utf-8')).toMatchInlineSnapshot(
203+
`"const port = 9999;"`
204+
);
205+
});
206+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
import {
2+
ProjectConfiguration,
3+
type Tree,
4+
getProjects,
5+
joinPathFragments,
6+
visitNotIgnoredFiles,
7+
} from '@nx/devkit';
8+
import { tsquery } from '@phenomnomnominal/tsquery';
9+
import * as ts from 'typescript';
10+
import { minimatch } from 'minimatch';
11+
import { forEachExecutorOptions } from '@nx/devkit/src/generators/executor-options-utils';
12+
import { type WebSsrDevServerOptions } from '@nx/webpack/src/executors/ssr-dev-server/schema';
13+
14+
export default function update(tree: Tree) {
15+
const projects = getProjects(tree);
16+
const executors = [
17+
'@nx/webpack:ssr-dev-server',
18+
'@nx/react:module-federation-ssr-dev-server',
19+
];
20+
21+
executors.forEach((executor) => {
22+
forEachExecutorOptions<WebSsrDevServerOptions>(
23+
tree,
24+
executor,
25+
(options, projectName) => {
26+
const project = projects.get(projectName);
27+
if (isModuleFederationSSRProject(tree, project)) {
28+
const port = options.port;
29+
if (tree.exists(joinPathFragments(project.root, 'server.ts'))) {
30+
const serverContent = tree.read(
31+
joinPathFragments(project.root, 'server.ts'),
32+
'utf-8'
33+
);
34+
if (serverContent && port) {
35+
const updatedServerContent = updateServerPort(
36+
serverContent,
37+
port
38+
);
39+
if (updatedServerContent) {
40+
tree.write(
41+
joinPathFragments(project.root, 'server.ts'),
42+
updatedServerContent
43+
);
44+
}
45+
}
46+
}
47+
}
48+
}
49+
);
50+
});
51+
}
52+
53+
function updateServerPort(serverContent: string, port: number) {
54+
const sourceFile = tsquery.ast(serverContent);
55+
56+
const serverPortNode = tsquery(
57+
sourceFile,
58+
`VariableDeclaration:has(Identifier[name="port"])`
59+
)[0];
60+
if (serverPortNode) {
61+
const binaryExpression = tsquery(serverPortNode, 'BinaryExpression')[0];
62+
if (binaryExpression) {
63+
const leftExpression = tsquery(
64+
binaryExpression,
65+
'PropertyAccessExpression:has(Identifier[name="env"])'
66+
)[0];
67+
const rightExpression = tsquery(
68+
binaryExpression,
69+
'NumericLiteral[text="4200"]'
70+
)[0];
71+
72+
if (leftExpression && rightExpression) {
73+
const serverPortDeclaration = serverPortNode as ts.VariableDeclaration;
74+
const newInitializer = ts.factory.createBinaryExpression(
75+
// process.env.PORT
76+
ts.factory.createPropertyAccessExpression(
77+
ts.factory.createPropertyAccessExpression(
78+
ts.factory.createIdentifier('process'),
79+
ts.factory.createIdentifier('env')
80+
),
81+
'PORT'
82+
),
83+
// ||
84+
ts.SyntaxKind.BarBarToken,
85+
// port value
86+
ts.factory.createNumericLiteral(port.toString())
87+
);
88+
89+
const updatePortDeclaration = ts.factory.updateVariableDeclaration(
90+
serverPortDeclaration,
91+
serverPortDeclaration.name,
92+
serverPortDeclaration.exclamationToken,
93+
serverPortDeclaration.type,
94+
newInitializer
95+
);
96+
97+
const updatedStatements = sourceFile.statements.map((statement) => {
98+
if (ts.isVariableStatement(statement)) {
99+
const updatedDeclarationList =
100+
statement.declarationList.declarations.map((decl) =>
101+
decl === serverPortDeclaration ? updatePortDeclaration : decl
102+
);
103+
104+
const updatedDeclList = ts.factory.updateVariableDeclarationList(
105+
statement.declarationList,
106+
updatedDeclarationList
107+
);
108+
109+
return ts.factory.updateVariableStatement(
110+
statement,
111+
statement.modifiers,
112+
updatedDeclList
113+
);
114+
}
115+
116+
return statement;
117+
});
118+
119+
const updatedSourceFile = ts.factory.updateSourceFile(
120+
sourceFile,
121+
updatedStatements
122+
);
123+
124+
const printer = ts.createPrinter();
125+
return printer.printNode(
126+
ts.EmitHint.Unspecified,
127+
updatedSourceFile,
128+
sourceFile
129+
);
130+
}
131+
}
132+
}
133+
}
134+
135+
function isModuleFederationSSRProject(
136+
tree: Tree,
137+
project: ProjectConfiguration
138+
) {
139+
let hasMfeServerConfig = false;
140+
visitNotIgnoredFiles(tree, project.root, (filePath) => {
141+
if (minimatch(filePath, '**/module-federation*.server.config.*')) {
142+
hasMfeServerConfig = true;
143+
}
144+
});
145+
return hasMfeServerConfig;
146+
}

0 commit comments

Comments
 (0)