Skip to content

Commit

Permalink
fix: #61 (#63)
Browse files Browse the repository at this point in the history
Co-authored-by: 张洪恩 <zhanghongen@bwcj.com>
  • Loading branch information
zhangHongEn and 张洪恩 authored Aug 19, 2024
1 parent 0ffffa4 commit 51eeeb6
Show file tree
Hide file tree
Showing 8 changed files with 55 additions and 59 deletions.
12 changes: 6 additions & 6 deletions examples/vite-vite/vite-host/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@ export default defineConfig({
requiredVersion: '18',
},
'react-dom': {},
"ag-grid-community": {},
// "ag-grid-react": {},
// "@emotion/react": {},
// "styled-components": { singleton: true },
// "@emotion/styled": {},
// "@mui/material": {},
'ag-grid-community': {},
'ag-grid-react': {},
'@emotion/react': {},
'styled-components': { singleton: true },
'@emotion/styled': {},
'@mui/material': {},
},
runtimePlugins: ['./src/mfPlugins'],
}),
Expand Down
10 changes: 5 additions & 5 deletions examples/vite-vite/vite-remote/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ export default defineConfig({
},
'react-dom': {},
'styled-components': { singleton: true },
"ag-grid-community": {},
// "ag-grid-react": {},
// "@emotion/react": {},
// "@emotion/styled": { singleton: true, },
// "@mui/material": {},
'ag-grid-community': {},
'ag-grid-react': {},
'@emotion/react': {},
'@emotion/styled': { singleton: true },
'@mui/material': {},
},
}),
// If you set build.target: "chrome89", you can remove this plugin
Expand Down
2 changes: 0 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import pluginProxyRemoteEntry from './plugins/pluginProxyRemoteEntry';
import pluginProxyRemotes from './plugins/pluginProxyRemotes';
import { proxySharedModule } from './plugins/pluginProxySharedModule_preBuild';
import aliasToArrayPlugin from './utils/aliasToArrayPlugin';
import normalizeBuildPlugin from './utils/normalizeBuild';
import {
ModuleFederationOptions,
normalizeModuleFederationOptions
Expand All @@ -20,7 +19,6 @@ function federation(mfUserOptions: ModuleFederationOptions): Plugin[] {
return [
aliasToArrayPlugin,
normalizeOptimizeDepsPlugin,
normalizeBuildPlugin([...Object.keys(shared), "@module-federation/runtime"]),
...addEntry({
entryName: 'remoteEntry',
entryPath: WRAP_REMOTE_ENTRY_PATH,
Expand Down
1 change: 1 addition & 0 deletions src/plugins/pluginAddEntry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ const addEntry = ({ entryName, entryPath, fileName }: AddEntryOptions): Plugin[]
buildStart() {
const hasHash = fileName?.includes?.("[hash")
this.emitFile({
name: entryName,
[hasHash ? "name" : "fileName"]: fileName,
type: 'chunk',
id: entryPath,
Expand Down
32 changes: 25 additions & 7 deletions src/plugins/pluginProxySharedModule_preBuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import { walk } from 'estree-walker';
import MagicString from 'magic-string';
import { Plugin, UserConfig } from 'vite';
import { NormalizedShared } from '../utils/normalizeModuleFederationOptions';
import { getLoadShareModulePath, getPreBuildLibPath, writeLoadShareModule, writeLocalSharedImportMap } from '../virtualModules/virtualShared_preBuild';
import { wrapManualChunks } from '../utils/wrapManualChunks';
import { getLoadShareModulePath, getPreBuildLibPath, LOAD_SHARE_TAG, writeLoadShareModule, writeLocalSharedImportMap } from '../virtualModules/virtualShared_preBuild';
export function proxySharedModule(
options: { shared?: NormalizedShared; include?: string | string[]; exclude?: string | string[] }
): Plugin[] {
Expand All @@ -15,33 +16,50 @@ export function proxySharedModule(
name: 'preBuildShared',
enforce: 'post',
config(config: UserConfig, { command }) {
if (!config.build) config.build = {};
if (!config.build.rollupOptions) config.build.rollupOptions = {};
let { rollupOptions } = config.build;
if (!rollupOptions.output) rollupOptions.output = {};
// config?.optimizeDeps?.include?.push?.("an-empty-js-file");
// config.optimizeDeps.needsInterop.push('an-empty-js-file');
(config.resolve as any).alias.push(
wrapManualChunks(config.build.rollupOptions.output, (id: string) => {
if (id.includes("node_modules/@module-federation/runtime")) {
return "@module-federation/runtime"
}
if (id.includes(LOAD_SHARE_TAG) || id.includes("__mf__prebuildwrap_")) {
return id.split("/").pop()
}
});
; (config.resolve as any).alias.push(
...Object.keys(shared).map((key) => {
config?.optimizeDeps?.include?.push?.(getPreBuildLibPath(key));
// write proxyFile
writeLoadShareModule(key, shared[key], command)
const preBuildLibPath = getLoadShareModulePath(key)
config?.optimizeDeps?.needsInterop?.push(key);
return {
// Intercept all dependency requests to the proxy module
// Dependency requests issued by localSharedImportMap are allowed without proxying.
find: new RegExp(`^${key}$`), replacement: preBuildLibPath, customResolver(source: string, importer: string) {
if (importer.includes(`node_modules/${key}/`)) {
return (this as any).resolve(key)
}
config?.optimizeDeps?.needsInterop?.push(preBuildLibPath);
return (this as any).resolve(preBuildLibPath)
}
}
})
);
(config.resolve as any).alias.push(
...Object.keys(shared).map((key) => {
return {
find: new RegExp(`^${getPreBuildLibPath(key)}$`), customResolver(source: string, importer: string) {
return (this as any).resolve(key)
return command === "build" ?
{ find: new RegExp(`^${getPreBuildLibPath(key)}$`), replacement: key } :
{
find: new RegExp(`^${getPreBuildLibPath(key)}$`), customResolver(source: string, importer: string) {

return (this as any).resolve(key)
}
}
}
})
);
},
Expand Down Expand Up @@ -126,4 +144,4 @@ export function proxySharedModule(
},
}
]
}
}
38 changes: 0 additions & 38 deletions src/utils/normalizeBuild.ts

This file was deleted.

16 changes: 16 additions & 0 deletions src/utils/wrapManualChunks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export function wrapManualChunks(output: any, manualChunksCb: Function): void {
if (!output.manualChunks) output.manualChunks = {};
const wrapManualChunks =
(original: any) =>
(id: string, ...args: any[]) => {
const customRes = manualChunksCb?.(id, ...args)
if (customRes) return customRes
if (typeof original === 'function') {
return original(id, ...args);
}
if (typeof original === 'object' && original) {
return original[id];
}
};
output.manualChunks = wrapManualChunks(output.manualChunks);
}
3 changes: 2 additions & 1 deletion src/virtualModules/virtualShared_preBuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,14 @@ export function writeLocalSharedImportMap(pkgList: string[]) {
`)
}

export const LOAD_SHARE_TAG = "__mf__loadShare_"
/**
* generate loadShare virtual module
*/
const cacheMap1: Record<string, string> = {}
export function getLoadShareModulePath(pkg: string): string {
const { name } = getNormalizeModuleFederationOptions()
if (!cacheMap1[pkg]) cacheMap1[pkg] = npmPackageNameToFileName(name) + "_" + `__mf__loadShare_${npmPackageNameToFileName(pkg)}.js`
if (!cacheMap1[pkg]) cacheMap1[pkg] = npmPackageNameToFileName(name) + "_" + `${LOAD_SHARE_TAG}${npmPackageNameToFileName(pkg)}.js`
const filename = cacheMap1[pkg]
return resolve(emptyNpmDir, filename)
}
Expand Down

0 comments on commit 51eeeb6

Please sign in to comment.