Skip to content

Commit 17d3bad

Browse files
fix chunk flushing ssr preheats
1 parent 59a5d5e commit 17d3bad

File tree

5 files changed

+66
-22
lines changed

5 files changed

+66
-22
lines changed

flushChunksOrig.js

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,30 @@ const loadableManifest = requireMethod(requestPath);
1717
const flushChunks = async (remoteEnvVar = process.env.REMOTES) => {
1818
const remoteKeys = Object.keys(remoteEnvVar);
1919
const remotes = {};
20+
const preload = [];
21+
22+
for (const key in remoteEnvVar) {
23+
const remoteContainer = await remoteEnvVar[key]();
24+
if (
25+
remoteContainer &&
26+
remoteContainer.chunkMap &&
27+
remoteContainer.chunkMap.federatedModules
28+
) {
29+
remoteContainer.chunkMap.federatedModules.forEach((federatedRemote) => {
30+
Object.keys(federatedRemote.exposes).forEach(m => {
31+
preload.push(remoteContainer.get(m).then((f)=>{
32+
try {
33+
return f()
34+
} catch(e) {
35+
36+
}
37+
}))
38+
})
39+
})
40+
}
41+
}
42+
const preloaded = await Promise.all(preload)
43+
2044
try {
2145
for (const key in loadableManifest) {
2246
const [where, what] = key.split("->");
@@ -28,6 +52,7 @@ const flushChunks = async (remoteEnvVar = process.env.REMOTES) => {
2852
return null;
2953
}
3054
const remoteContainer = await remoteEnvVar[foundFederatedImport]();
55+
3156
const path = remoteContainer.path.split("@")[1];
3257
const [baseurl] = path.split("static/ssr");
3358
if (
@@ -44,6 +69,7 @@ const flushChunks = async (remoteEnvVar = process.env.REMOTES) => {
4469
});
4570
const request = `.${what.split(foundFederatedImport)[1]}`;
4671
federatedRemote.exposes[request].forEach((remoteChunks) => {
72+
4773
remoteChunks.chunks.map((chunk) => {
4874
if (
4975
!loadableManifest[key].files.includes(
@@ -68,7 +94,6 @@ const flushChunks = async (remoteEnvVar = process.env.REMOTES) => {
6894
}
6995
return [];
7096
};
71-
let flushStamp
7297
export class ExtendedHead extends Head {
7398
constructor(props, context) {
7499
super(props, context);
@@ -83,7 +108,7 @@ export class ExtendedHead extends Head {
83108
if (chunk.props.src.startsWith("/") && chunk.props.src.includes("http")) {
84109
return React.cloneElement(chunk, {
85110
...chunk.props,
86-
src: `http${chunk.props.src.split("http")[1]}`.replace('stamp',flushStamp),
111+
src: `http${chunk.props.src.split("http")[1]}`,
87112
});
88113
} else if (chunk.props.src.includes("-fed") && this.context.assetPrefix) {
89114
const replacedArg = this.context.assetPrefix.endsWith("/")
@@ -137,16 +162,19 @@ const revalidate = ()=>{
137162
});
138163
}
139164
}).then(()=>{
140-
flushStamp = Date.now()
141165
let req
142166
if(typeof __non_webpack_require__ === 'undefined') {
143167
req = require
144168
} else {
145169
req = __non_webpack_require__
146170
}
171+
if(global.hotLoad) {
172+
global.hotLoad()
173+
}
147174
Object.keys(req.cache).forEach((k) => {
148175
if(k.includes('remote') || k.includes('runtime') || k.includes('server')) {
149176
delete req.cache[k];
177+
// require(k);
150178
}
151179
})
152180
})

lib/with-federated-sidecar.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,9 +122,13 @@ const withModuleFederation =
122122

123123
if (options.isServer) {
124124
filteredPlugins.push(
125+
// new webpack.optimize.LimitChunkCountPlugin({
126+
// maxChunks: 1,
127+
// }),
125128
new webpack.container.ModuleFederationPlugin(federationPluginOptions),
126129
new NodeSoftwareStreamRuntime(federationPluginOptions, options)
127130
);
131+
128132
} else {
129133
filteredPlugins.push(
130134
new webpack.container.ModuleFederationPlugin(federationPluginOptions)
@@ -388,7 +392,7 @@ const withModuleFederation =
388392
res(window.${moduleName});
389393
}
390394
};
391-
script.src = '${scriptUrl}';
395+
script.src = '${scriptUrl}' + '?' + Date.now();
392396
if(existingScript) {
393397
if(window.${moduleName}) {
394398
script.onload()

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"public": true,
33
"name": "@module-federation/nextjs-ssr",
4-
"version": "0.0.1-beta.28",
4+
"version": "0.0.1-beta.33",
55
"description": "Module Federation CSR & SSR Support for Next.js",
66
"main": "load.js",
77
"types": "index.d.ts",

streaming/src/NodeAsyncHttpRuntime/LoadFileChunkLoadingRuntimeModule.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,6 @@ class ReadFileChunkLoadingRuntimeModule extends RuntimeModule {
8383
});`,
8484
])
8585
: "// no baseURI",
86-
"",
8786
`// var nonsense = ${Date.now()}`,
8887
"// object to store loaded chunks",
8988
'// "0" means "already loaded", Promise means loading',
@@ -169,12 +168,12 @@ class ReadFileChunkLoadingRuntimeModule extends RuntimeModule {
169168
var fileToReplace = require('path').basename(scriptUrl.pathname);
170169
scriptUrl.pathname = scriptUrl.pathname.replace(fileToReplace, chunkName);
171170
172-
console.log('remote chunk url', scriptUrl.toString());
171+
console.log('remote chunk url', scriptUrl.toString() + '?' + Date.now());
173172
`,
174173
`console.log('${promiseBaseURI}','${baseURI}', ${JSON.stringify(
175174
remotes
176175
)}, '${name}');`,
177-
`loadScript(scriptUrl.toString(), function(err, content) {`,
176+
`loadScript(scriptUrl.toString() + '?' + Date.now(), function(err, content) {`,
178177
Template.indent([
179178
"if(err) return reject(err);",
180179
"var chunk = {};",

streaming/src/NodeModuleFederation/index.js

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -23,28 +23,35 @@ const executeLoadTemplate = `
2323
`;
2424

2525
const processRemoteLoadTemplate = (mfConfig) => `
26-
function processRemoteLoad(remote, name, path) {
27-
return {
28-
get:(request)=> remote.get(request),
26+
function processRemoteLoad(remote, name, path) {
27+
return Promise.all(Object.keys(remote.chunkMap.federatedModules[0].exposes).map(c=>{
28+
return remote.get(c).then(f=>{
29+
try {f()} catch(e) {}
30+
})
31+
})).then(()=>{
32+
const prox= {
33+
get: remote.get,
2934
chunkMap: remote.chunkMap,
3035
path: path,
3136
init:(arg)=>{try {return remote.init({
3237
...arg,
3338
${Object.keys(mfConfig.shared || {})
34-
.filter(
35-
(item) =>
36-
mfConfig.shared[item].singleton &&
37-
mfConfig.shared[item].requiredVersion
38-
)
39-
.map(function (item) {
40-
return `"${item}": {
39+
.filter(
40+
(item) =>
41+
mfConfig.shared[item].singleton &&
42+
mfConfig.shared[item].requiredVersion
43+
)
44+
.map(function (item) {
45+
return `"${item}": {
4146
["${mfConfig.shared[item].requiredVersion}"]: {
4247
get: () => Promise.resolve().then(() => () => require("${item}"))
4348
}
4449
}`;
45-
})
46-
.join(",")}
50+
})
51+
.join(",")}
4752
})} catch(e){console.log('remote container already initialized')}}}
53+
return prox
54+
})
4855
}
4956
`;
5057

@@ -58,9 +65,15 @@ function buildRemotes(mfConf) {
5865
(acc, [name, config]) => {
5966
const template = `new Promise(function(res) {
6067
${builtinsTemplate}
61-
res(executeLoad("${config}").then(function(remote){return processRemoteLoad(remote,${JSON.stringify(
68+
global.loadedRemotes = global.loadedRemotes || {};
69+
if(global.loadedRemotes[${JSON.stringify(name)}]) {
70+
res(global.loadedRemotes[${JSON.stringify(name)}])
71+
return
72+
}
73+
global.loadedRemotes[${JSON.stringify(name)}] = executeLoad("${config}").then(function(remote){return processRemoteLoad(remote,${JSON.stringify(
6274
name
63-
)},"${config}")}))
75+
)},"${config}")})
76+
res(global.loadedRemotes[${JSON.stringify(name)}])
6477
})`;
6578
acc.runtime[name] = `()=> ${template}`;
6679
acc.buildTime[name] = `promise ${template}`;

0 commit comments

Comments
 (0)