Skip to content

Commit

Permalink
fix: css flickering issue
Browse files Browse the repository at this point in the history
  • Loading branch information
2heal1 committed Sep 12, 2024
1 parent 4cfa4c8 commit 17504a1
Show file tree
Hide file tree
Showing 16 changed files with 231 additions and 135 deletions.
8 changes: 7 additions & 1 deletion apps/modernjs-ssr-data-loader/host/modern.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,19 @@ export default defineConfig({
router: true,
},
server: {
// baseUrl: '/kkkk',
ssr: {
mode: 'stream',
},
ssrByRouteIds: ['entry-one_nested-routes/pathname/layout', 'remote@layout'],
port: 3062,
},
source: {
alias: {
// FIXME: becasue modernjs set alias value as package, so the value will use @module-federation/modern-js's @modern-js/runtime , and it will cause multiple instance
'@meta/runtime':
'/Users/bytedance/outter/universe/node_modules/.pnpm/@[email protected]_@[email protected]_@[email protected][email protected][email protected]/node_modules/@modern-js/runtime/dist/esm/index.js',
},
},
plugins: [
appTools({
bundler: 'experimental-rspack',
Expand Down
8 changes: 8 additions & 0 deletions packages/modernjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@
"types": "./dist/types/runtime/dataLoader/plugin.d.ts",
"default": "./dist/esm/runtime/dataLoader/plugin.js"
},
"./data-loader-inject-assets": {
"types": "./dist/types/runtime/dataLoader/plugin-inject-assets.d.ts",
"default": "./dist/esm/runtime/dataLoader/plugin-inject-assets.js"
},
"./data-loader-server": {
"types": "./dist/types/cli/server/dataLoaderPlugin.d.ts",
"default": "./dist/cjs/cli/server/dataLoaderPlugin.js"
Expand Down Expand Up @@ -70,6 +74,9 @@
"data-loader": [
"./dist/types/runtime/dataLoader/plugin.d.ts"
],
"data-loader-inject-assets": [
"./dist/types/runtime/dataLoader/plugin-inject-assets.d.ts"
],
"data-loader-server": [
"./dist/types/cli/server/dataLoaderPlugin.d.ts"
]
Expand Down Expand Up @@ -107,6 +114,7 @@
"@modern-js/tsconfig": "^2.59.0"
},
"peerDependencies": {
"@modern-js/runtime": "^2.59.0",
"react": ">=17",
"react-dom": ">=17",
"typescript": "^4.9.0 || ^5.0.0",
Expand Down
34 changes: 28 additions & 6 deletions packages/modernjs/src/cli/dataLoader/patchMFConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ type PatchMFConfigOptions = {
function generateExtraExposeFiles(options: PatchMFConfigOptions) {
const { internalDirectory, mfConfig, isServer, entries } = options;
const entryMap: {
[entryName: string]: { routesPath: string; routeServerLoaderPath: string };
[entryName: string]: {
routesPath: string;
routeServerLoaderPath: string;
clientRouteServerLoaderPath: string;
};
} = {};

const outputDir = path.resolve(
Expand Down Expand Up @@ -63,6 +67,10 @@ function generateExtraExposeFiles(options: PatchMFConfigOptions) {
outputEntryDir,
`${MODERN_JS_ROUTE_SERVER_LOADER}.js`,
);
const clientRouteServerLoaderPath = outputRouteServerLoaderPath.replace(
MODERN_JS_ROUTE_SERVER_LOADER,
`${MODERN_JS_ROUTE_SERVER_LOADER}-client`,
);
if (isServer) {
const routeServerLoaderContent = fs.readFileSync(
routeServerLoaderPath,
Expand All @@ -72,11 +80,14 @@ function generateExtraExposeFiles(options: PatchMFConfigOptions) {
sourceCode: routeServerLoaderContent,
filePath: outputRouteServerLoaderPath,
});
} else {
fs.writeFileSync(clientRouteServerLoaderPath, `export const routes = []`);
}

entryMap[entry] = {
routesPath: outputFullRoutesPath,
routeServerLoaderPath: outputRouteServerLoaderPath,
clientRouteServerLoaderPath,
};
};
entries.forEach((entry) => {
Expand All @@ -90,14 +101,15 @@ function generateExtraExposeFiles(options: PatchMFConfigOptions) {
function addExpose(options: PatchMFConfigOptions) {
const { mfConfig, isServer } = options;
if (mfConfig.remotes && mfConfig.exposes) {
throw new Error(`dataLoader only support for pure provider/consumer !`);
throw new Error(`dataLoader only support for pure provider/consumer!`);
}
const { entryMap } = generateExtraExposeFiles(options);

const addExposeByEntry = (
entry: string,
routesPath: string,
routeServerLoaderPath: string,
clientRouteServerLoaderPath: string,
) => {
if (!mfConfig.exposes) {
mfConfig.exposes = {};
Expand All @@ -108,14 +120,24 @@ function addExpose(options: PatchMFConfigOptions) {
mfConfig.exposes[routesKey] = routesPath;
}
const routeServerLoaderKey = `./${entry}/${MODERN_JS_ROUTE_SERVER_LOADER}`;
if (isServer && !mfConfig.exposes[routeServerLoaderKey]) {
mfConfig.exposes[routeServerLoaderKey] = routeServerLoaderPath;
if (!mfConfig.exposes[routeServerLoaderKey]) {
if (isServer) {
mfConfig.exposes[routeServerLoaderKey] = routeServerLoaderPath;
} else {
mfConfig.exposes[routeServerLoaderKey] = clientRouteServerLoaderPath;
}
}
};

Object.keys(entryMap).forEach((entry) => {
const { routesPath, routeServerLoaderPath } = entryMap[entry];
addExposeByEntry(entry, routesPath, routeServerLoaderPath);
const { routesPath, routeServerLoaderPath, clientRouteServerLoaderPath } =
entryMap[entry];
addExposeByEntry(
entry,
routesPath,
routeServerLoaderPath,
clientRouteServerLoaderPath,
);
});
}
function addShared(options: PatchMFConfigOptions) {
Expand Down
7 changes: 6 additions & 1 deletion packages/modernjs/src/cli/dataLoader/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type {
InternalModernPluginOptions,
} from '../../types';
import type { init } from '@module-federation/enhanced/runtime';
import { transformName2Prefix } from '../../runtime/utils';
import { transformName2Prefix } from '../../runtime/dataLoader/utils';
import { DEFAULT_ENTRY } from '../../constant';
import { META_NAME } from '../../constant';
import { generateRoutes } from './ast';
Expand Down Expand Up @@ -94,6 +94,11 @@ export const moduleFederationDataLoaderPlugin = (
path: '@module-federation/modern-js/data-loader',
config: {},
});
plugins.push({
name: 'ssrDataLoaderInjectAssets',
path: '@module-federation/modern-js/data-loader-inject-assets',
config: {},
});
return { entrypoint, plugins };
},
_internalServerPlugins({ plugins }) {
Expand Down
18 changes: 0 additions & 18 deletions packages/modernjs/src/cli/mfRuntimePlugins/inject-node-fetch.ts

This file was deleted.

14 changes: 14 additions & 0 deletions packages/modernjs/src/cli/mfRuntimePlugins/node-fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { FederationRuntimePlugin } from '@module-federation/enhanced/runtime';
import nodeFetch from 'node-fetch';

const injectNodeFetchPlugin: () => FederationRuntimePlugin = () => ({
name: 'node-fetch-plugin',
beforeInit(args) {
if (!globalThis.fetch) {
// @ts-expect-error inject node-fetch
globalThis.fetch = nodeFetch;
}
return args;
},
});
export default injectNodeFetchPlugin;
26 changes: 15 additions & 11 deletions packages/modernjs/src/cli/mfRuntimePlugins/node.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import type { FederationRuntimePlugin } from '@module-federation/enhanced/runtime';
import nodeFetch from 'node-fetch';
import nodeRuntimePlugin from '@module-federation/node/runtimePlugin';

const injectNodeFetchPlugin: () => FederationRuntimePlugin = () => ({
name: 'inject-node-fetch-plugin',
beforeInit(args) {
if (!globalThis.fetch) {
// @ts-expect-error inject node-fetch
globalThis.fetch = nodeFetch;
}
return args;
},
// TODO: Support pass params in runtimePlugins , supports pass different params via env.
const isContainer =
typeof __filename === 'string'
? __filename.includes('remote')
? true
: false
: false;
const pluginName = `node-plugin-${isContainer}`;

const nodePlugin: () => FederationRuntimePlugin = () => ({
name: pluginName,
beforeInit: nodeRuntimePlugin().beforeInit,
});
export default injectNodeFetchPlugin;

export default nodePlugin;
22 changes: 0 additions & 22 deletions packages/modernjs/src/cli/mfRuntimePlugins/shared-strategy.ts

This file was deleted.

11 changes: 5 additions & 6 deletions packages/modernjs/src/cli/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ describe('patchMFConfig', async () => {
remote: `http://${ipv4}:3000/remoteEntry.js`,
},
remoteType: 'script',
shareStrategy: 'loaded-first',
runtimePlugins: [
path.resolve(__dirname, './mfRuntimePlugins/shared-strategy.js'),
require.resolve('./mfRuntimePlugins/node.js'),
path.resolve(__dirname, './mfRuntimePlugins/inject-node-fetch.js'),
path.resolve(__dirname, './mfRuntimePlugins/node.js'),
path.resolve(__dirname, './mfRuntimePlugins/node-fetch.js'),
],
shared: {
react: {
Expand All @@ -68,9 +68,8 @@ describe('patchMFConfig', async () => {
remote: `http://${ipv4}:3000/remoteEntry.js`,
},
remoteType: 'script',
runtimePlugins: [
path.resolve(__dirname, './mfRuntimePlugins/shared-strategy.js'),
],
runtimePlugins: [],
shareStrategy: 'loaded-first',
shared: {
react: {
eager: true,
Expand Down
11 changes: 3 additions & 8 deletions packages/modernjs/src/cli/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,14 +148,9 @@ export const patchMFConfig = (
throw new Error(`${PLUGIN_IDENTIFIER} mfConfig.name can not be empty!`);
}
const runtimePlugins = [...(mfConfig.runtimePlugins || [])];

mfConfig.shareStrategy = mfConfig.shareStrategy ?? 'loaded-first';
patchDTSConfig(mfConfig, isServer);

injectRuntimePlugins(
path.resolve(__dirname, './mfRuntimePlugins/shared-strategy.js'),
runtimePlugins,
);

if (isDev) {
injectRuntimePlugins(
path.resolve(__dirname, './mfRuntimePlugins/resolve-entry-ipv4.js'),
Expand All @@ -165,7 +160,7 @@ export const patchMFConfig = (

if (isServer) {
injectRuntimePlugins(
require.resolve('./mfRuntimePlugins/node.js'),
path.resolve(__dirname, './mfRuntimePlugins/node.js'),
runtimePlugins,
);
if (isDev) {
Expand All @@ -178,7 +173,7 @@ export const patchMFConfig = (
}

injectRuntimePlugins(
path.resolve(__dirname, './mfRuntimePlugins/inject-node-fetch.js'),
path.resolve(__dirname, './mfRuntimePlugins/node-fetch.js'),
runtimePlugins,
);

Expand Down
6 changes: 6 additions & 0 deletions packages/modernjs/src/global.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
declare module '@meta/runtime' {
export * from '@modern-js/runtime';
}
declare module '@meta/runtime/router' {
export * from '@modern-js/runtime/router';
}
60 changes: 60 additions & 0 deletions packages/modernjs/src/runtime/dataLoader/plugin-inject-assets.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { useContext } from 'react';
import type { Plugin } from '@modern-js/runtime';
import { getInstance } from '@module-federation/enhanced/runtime';
import { collectSSRAssets } from '../createRemoteSSRComponent';
import { RuntimeReactContext } from '@meta/runtime';
import { decodeId, getRemoteId } from './utils';

export const ssrDataLoaderInjectAssetsPlugin = (): Plugin => {
return {
name: '@modern-js/plugin-mf-data-loader-inject-assets',
pre: ['@modern-js/plugin-router', '@modern-js/plugin-mf-data-loader'],
setup: () => {
return {
wrapRoot(App) {
const AppWrapper = (props: any) => {
const instance = getInstance();
if (!instance || !instance.options.remotes.length) {
return (
<>
<App {...props} />
</>
);
}
const context = useContext(RuntimeReactContext);
const { remotes } = instance.options;

const remoteNames =
context.routerContext?.matches.map((match) =>
decodeId(match.route.id),
) || [];
const remoteIds = remoteNames.reduce((sum, cur) => {
const matchRemote = remotes.find((r) => r.name === cur);
if (matchRemote) {
sum.add(getRemoteId(cur));
}
return sum;
}, new Set() as Set<string>);

const assets: React.ReactNode[] = [];
remoteIds.forEach((remoteId) => {
assets.push(
...collectSSRAssets({
id: remoteId,
}),
);
});

return (
<>
{assets}
<App {...props} />
</>
);
};
return AppWrapper;
},
};
},
};
};
2 changes: 2 additions & 0 deletions packages/modernjs/src/runtime/dataLoader/plugin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export const ssrDataLoaderPlugin = (): Plugin => {
post: ['@modern-js/plugin-router'],
setup: () => {
const remoteRoutesMap: RemoteRoutesMap = {};
const pathRemoteMap: Record<string, string> = {};
return {
async beforeRender() {
console.log('init');
Expand All @@ -36,6 +37,7 @@ export const ssrDataLoaderPlugin = (): Plugin => {
remoteRoutesMap[remote.name] = {
routes,
};
// pathRemoteMap[]
}),
);
},
Expand Down
Loading

0 comments on commit 17504a1

Please sign in to comment.