Skip to content

Commit

Permalink
fix: manage implementation option + fix circular import issue (#191)
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangHongEn authored Nov 25, 2024
1 parent 72403d5 commit a8a0102
Show file tree
Hide file tree
Showing 7 changed files with 52 additions and 8 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ export default defineConfig({
shared: ["vue"],
}),
],
server: {
origin: "http://localhost:{Your port}"
},
// Do you need to support build targets lower than chrome89?
// You can use 'vite-plugin-top-level-await' plugin for that.
build: {
Expand Down Expand Up @@ -106,6 +109,9 @@ export default defineConfig({
shared: ["vue"],
}),
],
server: {
origin: "http://localhost:{Your port}"
},
// Do you need to support build targets lower than chrome89?
// You can use 'vite-plugin-top-level-await' plugin for that.
build: {
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ function federation(mfUserOptions: ModuleFederationOptions): Plugin[] {
// TODO: singleton
(config.resolve as any).alias.push({
find: '@module-federation/runtime',
replacement: require.resolve('@module-federation/runtime'),
replacement: options.implementation,
});

config.optimizeDeps?.include?.push('@module-federation/runtime');
Expand Down
1 change: 1 addition & 0 deletions src/plugins/pluginAddEntry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ const addEntry = ({
});
},
transformIndexHtml(c) {
if (inject !== 'html') return;
return c.replace(
'<head>',
`<head><script type="module" src=${JSON.stringify(
Expand Down
24 changes: 24 additions & 0 deletions src/plugins/pluginProxyRemoteEntry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { getNormalizeModuleFederationOptions } from '../utils/normalizeModuleFed
import {
generateExposes,
generateRemoteEntry,
getHostAutoInitPath,
REMOTE_ENTRY_ID,
VIRTUAL_EXPOSES,
} from '../virtualModules';
Expand All @@ -12,16 +13,26 @@ import { parsePromise } from './pluginModuleParseEnd';
const filter: (id: string) => boolean = createFilter();

export default function (): Plugin {
let viteConfig: any, _command: string;
return {
name: 'proxyRemoteEntry',
enforce: 'post',
configResolved(config) {
viteConfig = config;
},
config(config, { command }) {
_command = command;
},
resolveId(id: string) {
if (id === REMOTE_ENTRY_ID) {
return REMOTE_ENTRY_ID;
}
if (id === VIRTUAL_EXPOSES) {
return VIRTUAL_EXPOSES;
}
if (_command === 'serve' && id.includes(getHostAutoInitPath())) {
return id;
}
},
load(id: string) {
if (id === REMOTE_ENTRY_ID) {
Expand All @@ -30,6 +41,9 @@ export default function (): Plugin {
if (id === VIRTUAL_EXPOSES) {
return generateExposes();
}
if (_command === 'serve' && id.includes(getHostAutoInitPath())) {
return id;
}
},
async transform(code: string, id: string) {
if (!filter(id)) return;
Expand All @@ -39,6 +53,16 @@ export default function (): Plugin {
if (id === VIRTUAL_EXPOSES) {
return generateExposes();
}
if (id.includes(getHostAutoInitPath())) {
const options = getNormalizeModuleFederationOptions();
if (_command === 'serve') {
return `
const {init} = await import("//localhost:${viteConfig.server?.port}${viteConfig.base + options.filename}")
init()
`;
}
return code;
}
},
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ describe('normalizeModuleFederationOption', () => {
shared: {},
runtime: undefined,
runtimePlugins: [],
implementation: undefined,
implementation: require.resolve('@module-federation/runtime'),
manifest: false,
dev: undefined,
dts: undefined,
Expand Down
6 changes: 3 additions & 3 deletions src/utils/normalizeModuleFederationOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ export type ModuleFederationOptions = {
| undefined;
runtimePlugins?: string[];
getPublicPath?: string;
implementation?: any;
implementation?: string;
manifest?: ManifestOptions | boolean;
dev?: boolean | PluginDevOptions;
dts?: boolean | PluginDtsOptions;
Expand All @@ -263,7 +263,7 @@ export interface NormalizedModuleFederationOptions {
shareScope: string;
shared: NormalizedShared;
runtimePlugins: string[];
implementation: any;
implementation: string;
manifest: ManifestOptions | boolean;
dev?: boolean | PluginDevOptions;
dts?: boolean | PluginDtsOptions;
Expand Down Expand Up @@ -338,7 +338,7 @@ export function normalizeModuleFederationOptions(
shareScope: options.shareScope || 'default',
shared: normalizeShared(options.shared),
runtimePlugins: options.runtimePlugins || [],
implementation: options.implementation,
implementation: options.implementation || require.resolve('@module-federation/runtime'),
manifest: normalizeManifest(options.manifest),
dev: options.dev,
dts: options.dts,
Expand Down
19 changes: 16 additions & 3 deletions src/virtualModules/virtualRemoteEntry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,17 +120,30 @@ export function generateRemoteEntry(options: NormalizedModuleFederationOptions):
import {
initResolve
} from "${virtualRuntimeInitStatus.getImportId()}"
async function init(shared = {}) {
const initTokens = {}
const shareScopeName = ${JSON.stringify(options.shareScope)}
const mfName = ${JSON.stringify(options.name)}
async function init(shared = {}, initScope = []) {
const initRes = runtimeInit({
name: ${JSON.stringify(options.name)},
name: mfName,
remotes: usedRemotes,
shared: usedShared,
plugins: [${pluginImportNames.map((item) => `${item[0]}()`).join(', ')}],
${options.shareStrategy ? `shareStrategy: '${options.shareStrategy}'` : ''}
});
// handling circular init calls
var initToken = initTokens[shareScopeName];
if (!initToken)
initToken = initTokens[shareScopeName] = { from: mfName };
if (initScope.indexOf(initToken) >= 0) return;
initScope.push(initToken);
initRes.initShareScopeMap('${options.shareScope}', shared);
try {
await Promise.all(await initRes.initializeSharing('${options.shareScope}', {strategy: '${options.shareStrategy}'}));
await Promise.all(await initRes.initializeSharing('${options.shareScope}', {
strategy: '${options.shareStrategy}',
from: "build",
initScope
}));
} catch (e) {
console.error(e)
}
Expand Down

0 comments on commit a8a0102

Please sign in to comment.