Skip to content

Commit 3cb799b

Browse files
committed
fix: optimize code
1 parent 1a92081 commit 3cb799b

File tree

1 file changed

+29
-15
lines changed

1 file changed

+29
-15
lines changed

packages/icestark/src/util/handleAssets.ts

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,34 @@ const cachedProcessedContent: object = {};
2121

2222
const defaultFetch = window?.fetch.bind(window);
2323

24+
/**
25+
* Generate runtime library freeze code.
26+
* Used to prevent micro apps from reloading the same version of a runtime library.
27+
* @param versionedLibKey The versioned library key, formatted as "library@version"
28+
* @returns The generated freeze code string
29+
*/
30+
function generateRuntimeLockCode(versionedLibKey: string): string {
31+
const valueKey = `__${versionedLibKey}_value`;
32+
const warningMessage = `${versionedLibKey} is locked, cannot be modified`;
33+
34+
return `
35+
Object.defineProperty(window, '${versionedLibKey}', {
36+
get: function() {
37+
return this['${valueKey}'];
38+
},
39+
set: function(value) {
40+
if (this['${valueKey}'] === undefined) {
41+
this['${valueKey}'] = value;
42+
} else {
43+
console.warn('${warningMessage}');
44+
}
45+
},
46+
configurable: false,
47+
enumerable: true
48+
});
49+
`;
50+
}
51+
2452
export enum AssetTypeEnum {
2553
INLINE = 'inline',
2654
EXTERNAL = 'external',
@@ -328,21 +356,7 @@ export async function fetchScripts(jsList: Asset[], fetch: Fetch = defaultFetch)
328356
// 如果启用了冻结功能,添加冻结逻辑
329357
let lockCode = '';
330358
if (globalConfiguration.freezeRuntime) {
331-
lockCode = `
332-
Object.defineProperty(window, '${versionedLibKey}', {
333-
get: function() { return this['__${versionedLibKey}_value']; },
334-
set: function(value) {
335-
if (this['__${versionedLibKey}_value'] === undefined) {
336-
this['__${versionedLibKey}_value'] = value;
337-
} else {
338-
console.warn('${versionedLibKey} is locked, cannot be modified');
339-
}
340-
},
341-
configurable: false,
342-
enumerable: true
343-
});
344-
}
345-
`;
359+
lockCode = generateRuntimeLockCode(versionedLibKey);
346360
}
347361
jsBeforeRuntime = `${jsBeforeRuntime}${backupCode}${asset.loaded ? `${globalLib} = ${versionedLib};` : lockCode}`;
348362
jsAfterRuntime = `${jsAfterRuntime}${asset.loaded ? '' : `${versionedLib} = ${globalLib};`}${restoreCode}`;

0 commit comments

Comments
 (0)