Skip to content

feat: add remotePlugin option to control shared module bundling #327

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { VIRTUAL_EXPOSES } from './virtualModules/virtualExposes';

function federation(mfUserOptions: ModuleFederationOptions): Plugin[] {
const options = normalizeModuleFederationOptions(mfUserOptions);
const { name, remotes, shared, filename } = options;
const { name, remotes, shared, filename, remotePlugin } = options;
if (!name) throw new Error('name is required');

return [
Expand All @@ -47,11 +47,13 @@ function federation(mfUserOptions: ModuleFederationOptions): Plugin[] {
entryPath: REMOTE_ENTRY_ID,
fileName: filename,
}),
...addEntry({
entryName: 'hostInit',
entryPath: getHostAutoInitPath(),
inject: 'html',
}),
...(remotePlugin
? []
: addEntry({
entryName: 'hostInit',
entryPath: getHostAutoInitPath(),
inject: 'html',
})),
...addEntry({
entryName: 'virtualExposes',
entryPath: VIRTUAL_EXPOSES,
Expand Down
5 changes: 4 additions & 1 deletion src/plugins/pluginProxySharedModule_preBuild.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { Plugin, UserConfig } from 'vite';
import { NormalizedShared } from '../utils/normalizeModuleFederationOptions';
import {
NormalizedShared,
getNormalizeModuleFederationOptions,
} from '../utils/normalizeModuleFederationOptions';
import { PromiseStore } from '../utils/PromiseStore';
import VirtualModule from '../utils/VirtualModule';
import {
Expand Down
15 changes: 15 additions & 0 deletions src/utils/normalizeModuleFederationOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,10 @@ export type ModuleFederationOptions = {
filename?: string;
library?: any;
name: string;
/**
* When true, prevents shared modules from being bundled into remotes
* and makes them rely on host-provided shared modules at runtime
*/
// remoteType?: string;
remotes?: Record<string, string | RemoteObjectConfig> | undefined;
runtime?: any;
Expand Down Expand Up @@ -301,13 +305,23 @@ export type ModuleFederationOptions = {
shareStrategy?: ShareStrategy;
ignoreOrigin?: boolean;
virtualModuleDir?: string;
/**
* When true, prevents shared modules from being bundled into remotes
* and makes them rely on host-provided shared modules at runtime
*/
remotePlugin?: boolean;
};

export interface NormalizedModuleFederationOptions {
exposes: Record<string, ExposesItem>;
filename: string;
library: any;
name: string;
/**
* When true, prevents shared modules from being bundled into remotes
* and makes them rely on host-provided shared modules at runtime
*/
remotePlugin: boolean;
// remoteType: string;
remotes: Record<string, RemoteObjectConfig>;
runtime: any;
Expand Down Expand Up @@ -393,6 +407,7 @@ export function normalizeModuleFederationOptions(
return (config = {
exposes: normalizeExposes(options.exposes),
filename: options.filename || 'remoteEntry-[hash]',
remotePlugin: options.remotePlugin ?? false,
library: normalizeLibrary(options.library),
name: options.name,
// remoteType: options.remoteType,
Expand Down
39 changes: 24 additions & 15 deletions src/virtualModules/virtualRemoteEntry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,25 +37,33 @@ export function writeLocalSharedImportMap() {
}
export function generateLocalSharedImportMap() {
const options = getNormalizeModuleFederationOptions();

return `
const importMap = {
${Array.from(getUsedShares())
.map(
(pkg) => `
${
options.remotePlugin
? ''
: Array.from(getUsedShares())
.map(
(pkg) => `
${JSON.stringify(pkg)}: async () => {
let pkg = await import("${getPreBuildLibImportId(pkg)}")
return pkg
}
`
)
.join(',')}
)
.join(',')
}
}
const usedShared = {
${Array.from(getUsedShares())
.map((key) => {
const shareItem = getNormalizeShareItem(key);
if (!shareItem) return null;
return `
${
options.remotePlugin
? ''
: Array.from(getUsedShares())
.map((key) => {
const shareItem = getNormalizeShareItem(key);
if (!shareItem) return null;
return `
${JSON.stringify(key)}: {
name: ${JSON.stringify(key)},
version: ${JSON.stringify(shareItem.version)},
Expand All @@ -64,7 +72,7 @@ export function generateLocalSharedImportMap() {
from: ${JSON.stringify(options.name)},
async get () {
usedShared[${JSON.stringify(key)}].loaded = true
const {${JSON.stringify(key)}: pkgDynamicImport} = importMap
const {${JSON.stringify(key)}: pkgDynamicImport} = importMap
const res = await pkgDynamicImport()
const exportModule = {...res}
// All npm packages pre-built by vite will be converted to esm
Expand All @@ -82,9 +90,10 @@ export function generateLocalSharedImportMap() {
}
}
`;
})
.filter((x) => x !== null)
.join(',')}
})
.filter((x) => x !== null)
.join(',')
}
}
const usedRemotes = [${Object.keys(getUsedRemotesMap())
.map((key) => {
Expand Down Expand Up @@ -176,7 +185,7 @@ const hostAutoInitModule = new VirtualModule('hostAutoInit', HOST_AUTO_INIT_TAG)
export function writeHostAutoInit() {
hostAutoInitModule.writeSync(`
const remoteEntryPromise = import("${REMOTE_ENTRY_ID}")
// __tla only serves as a hack for vite-plugin-top-level-await.
// __tla only serves as a hack for vite-plugin-top-level-await.
Promise.resolve(remoteEntryPromise)
.then(remoteEntry => {
return Promise.resolve(remoteEntry.__tla)
Expand Down
2 changes: 1 addition & 1 deletion src/virtualModules/virtualShared_preBuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export function getLoadShareModulePath(pkg: string): string {
}
export function writeLoadShareModule(pkg: string, shareItem: ShareItem, command: string) {
loadShareCacheMap[pkg].writeSync(`

;() => import(${JSON.stringify(getPreBuildLibImportId(pkg))}).catch(() => {});
// dev uses dynamic import to separate chunks
${command !== 'build' ? `;() => import(${JSON.stringify(pkg)}).catch(() => {});` : ''}
Expand Down
Loading