Skip to content

Commit

Permalink
feat: try rspack and fix entry problems
Browse files Browse the repository at this point in the history
  • Loading branch information
yimingjfe committed Jan 2, 2025
1 parent 469dde7 commit 2253662
Show file tree
Hide file tree
Showing 6 changed files with 173 additions and 113 deletions.
16 changes: 11 additions & 5 deletions packages/cli/uni-builder/src/shared/rsc/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import type {
Compilation,
LoaderDefinitionFunction,
ModuleGraph,
NormalModule,
Module as WebpackModule,
} from 'webpack';

Expand Down Expand Up @@ -332,11 +333,16 @@ export function getServerActions(ast: Module): ServerAction[] {
return collector.getServerActions();
}

export function findRootIssuer(module: WebpackModule): WebpackModule {
let currentModule = module;
while (currentModule?.issuer) {
currentModule = currentModule.issuer;
export function findRootIssuer(
modulegraph: ModuleGraph,
module: NormalModule,
): NormalModule {
const currentModule = module;
const issuer = modulegraph.getIssuer(currentModule);

if (!issuer) {
return currentModule;
}

return currentModule;
return findRootIssuer(modulegraph, issuer as NormalModule);
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,17 @@ export const rscRsbuildPlugin = ({
setup(api) {
api.modifyBundlerChain({
handler: async (chain, { isServer, CHAIN_ID }) => {
const entryPath2Name = new Map<string, string>();

for (const [name, entry] of Object.entries(
chain.entryPoints.entries(),
)) {
entry.values().forEach(value => {
entryPath2Name.set(value as unknown as string, name);
});
}
const jsHandler = () => {
const originalJsRule = chain.module.rules.get(CHAIN_ID.RULE.JS);
const entryPath2Name = new Map<string, string>();

for (const [name, entry] of Object.entries(
chain.entryPoints.entries(),
)) {
entry.values().forEach(value => {
entryPath2Name.set(value as unknown as string, name);
});
}

const useBabel = originalJsRule.uses.has(CHAIN_ID.USE.BABEL);

Expand Down Expand Up @@ -112,7 +112,11 @@ export const rscRsbuildPlugin = ({
const ServerPlugin = isRspack
? RspackRscServerPlugin
: RscServerPlugin;
chain.plugin('rsc-server-plugin').use(ServerPlugin);
chain.plugin('rsc-server-plugin').use(ServerPlugin, [
{
entryPath2Name,
},
]);
};

const addRscClientLoader = () => {
Expand Down
100 changes: 77 additions & 23 deletions packages/cli/uni-builder/src/shared/rsc/plugins/rsc-server-plugin.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import type Webpack from 'webpack';
import {
type Compilation,
Module,
type ModuleGraph,
NormalModule,
} from 'webpack';
import {
type ServerManifest,
type ServerReferencesMap,
Expand All @@ -13,31 +19,80 @@ import type { ClientReferencesMap } from '../common';

export interface RscServerPluginOptions {
readonly serverManifestFilename?: string;
readonly entryPath2Name: Map<string, string>;
}

export interface ModuleExportsInfo {
readonly moduleResource: string;
readonly exportName: string;
}

const resourcePath2Entry = new Map<
const resourcePath2Entries = new Map<
string,
{
entryName: string;
entryPath: string;
}
}[]
>();

export class RscServerPlugin {
private clientReferencesMap: ClientReferencesMap = new Map();
private serverReferencesMap: ServerReferencesMap = new Map();
private serverManifest: ServerManifest = {};
private serverManifestFilename: string;
private entryPath2Name = new Map<string, string>();
private styles: Set<string>;
constructor(options: RscServerPluginOptions) {
this.styles = new Set();

this.serverManifestFilename =
options?.serverManifestFilename || `react-server-manifest.json`;

this.entryPath2Name = options?.entryPath2Name || new Map();
}

private findModuleEntries(
module: NormalModule,
compilation: Compilation,
resourcePath2Entries: Map<
string,
Array<{ entryName: string; entryPath: string }>
>,
visited = new Set<string>(),
): Array<{ entryName: string; entryPath: string }> {
if (!module?.resource || visited.has(module.resource)) {
return [];
}
visited.add(module.resource);

const currentEntries = resourcePath2Entries.get(module.resource);
if (currentEntries && currentEntries?.length > 0) {
return currentEntries;
}

const issuer = findRootIssuer(compilation.moduleGraph, module);
if (!issuer) {
return [];
}

const issuerEntries = this.findModuleEntries(
issuer,
compilation,
resourcePath2Entries,
visited,
);
if (issuerEntries.length > 0) {
return issuerEntries;
}

if (issuer.resource) {
const entryName = this.entryPath2Name.get(issuer.resource);
if (entryName) {
return [{ entryName, entryPath: issuer.resource }];
}
}

return [];
}

apply(compiler: Webpack.Compiler): void {
Expand Down Expand Up @@ -79,7 +134,7 @@ export class RscServerPlugin {
const includeModule = async (
compilation: Webpack.Compilation,
resource: string,
resourceEntryName?: string,
resourceEntryNames?: string[],
layer?: string,
) => {
const entries = Array.from(compilation.entries.entries());
Expand All @@ -93,7 +148,7 @@ export class RscServerPlugin {
}

const includePromises = entries
.filter(([entryName]) => entryName === resourceEntryName)
.filter(([entryName]) => resourceEntryNames?.includes(entryName))
.map(([entryName]) => {
const dependency = EntryPlugin.createDependency(resource, {
name: resource,
Expand Down Expand Up @@ -181,39 +236,38 @@ export class RscServerPlugin {
);
}

let entryName = buildInfo.__entryName;
let entryPath = buildInfo.__entryPath;
// server component -> client -component(react-server layer) -> client component(default layer) -> server action(default layer) -> server action(react-server layer)
if (!entryName) {
const entryModule = findRootIssuer(module);
const entryModuleBuildInfo = getRscBuildInfo(entryModule);
entryName = entryModuleBuildInfo.__entryName;
entryPath = entryModuleBuildInfo.__entryPath;
if (module instanceof NormalModule) {
// server component -> client -component(react-server layer) -> client component(default layer) -> server action(default layer) -> server action(react-server layer)
const entries = this.findModuleEntries(
module,
compilation,
resourcePath2Entries,
);
if (entries.length > 0) {
resourcePath2Entries.set(module.resource, entries);
}
}

resourcePath2Entry.set(buildInfo.resourcePath, {
entryName,
entryPath,
});
}

return hasChangeReference;
};

this.serverManifest = {};
let hasChangeReference = processModules(compilation.modules);

const clientReferences = [...this.clientReferencesMap.keys()];
const serverReferences = [...this.serverReferencesMap.keys()];
const referencesBefore = [...clientReferences, ...serverReferences];

let hasChangeReference = false;
await Promise.all([
...clientReferences.map(async resource => {
try {
await includeModule(
compilation,
resource,
resourcePath2Entry.get(resource)?.entryName || '',
resourcePath2Entries
.get(resource)
?.map(entry => entry.entryName) || [],
);
} catch (error) {
console.error(error);
Expand All @@ -226,7 +280,9 @@ export class RscServerPlugin {
await includeModule(
compilation,
resource,
resourcePath2Entry.get(resource)?.entryName || '',
resourcePath2Entries
.get(resource)
?.map(entry => entry.entryName) || [],
webpackRscLayerName,
);
} catch (error) {
Expand All @@ -237,8 +293,7 @@ export class RscServerPlugin {
}),
]);

hasChangeReference =
processModules(compilation.modules) || hasChangeReference;
hasChangeReference = processModules(compilation.modules);

const referencesAfter = [
...this.clientReferencesMap.keys(),
Expand All @@ -260,7 +315,6 @@ export class RscServerPlugin {
compiler.hooks.done.tap(RscServerPlugin.name, () => {
sharedData.set('serverReferencesMap', this.serverReferencesMap);
sharedData.set('clientReferencesMap', this.clientReferencesMap);
sharedData.set('resourcePath2Entry', resourcePath2Entry);
sharedData.set('styles', this.styles);
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ export class RspackRscClientPlugin {
const getEntryModule = (compilation: Webpack.Compilation): Module[] => {
const entryModules: Webpack.Module[] = [];

console.log('eeeeeeeeeeeee', compilation.entries);
for (const [, entryValue] of compilation.entries.entries()) {
// const entryDependency = entryValue.dependencies.find(
// dependency => dependency.constructor.name === `EntryDependency`,
Expand All @@ -73,23 +72,18 @@ export class RspackRscClientPlugin {
const resolvedModule =
compilation.moduleGraph.getModule(entryDependency);

console.log('resolvedModule1111111', resolvedModule);

if (resolvedModule) {
entryModules.push(resolvedModule);
}
}

console.log('2222222222', entryModules.length);

if (entryModules.length === 0) {
compilation.errors.push(
new WebpackError(`Could not find any entries in the compilation.`),
);
return [];
}

console.log('3333333333');
return entryModules;
};

Expand All @@ -105,7 +99,6 @@ export class RspackRscClientPlugin {
});
promises.push(
new Promise((resolve, reject) => {
console.log('before addInclude');
compilation.addInclude(
compiler.context,
dependency,
Expand All @@ -119,7 +112,6 @@ export class RspackRscClientPlugin {
}
},
);
console.log('after addInclude');
}),
);
});
Expand All @@ -131,7 +123,6 @@ export class RspackRscClientPlugin {
});
promises.push(
new Promise((resolve, reject) => {
console.log('before addInclude');
compilation.addInclude(
compiler.context,
dependency,
Expand All @@ -145,7 +136,6 @@ export class RspackRscClientPlugin {
}
},
);
console.log('after addInclude');
}),
);
}
Expand Down Expand Up @@ -178,9 +168,7 @@ export class RspackRscClientPlugin {
// }
// }

console.log('aaaaaaaaaaaa');
const entryModules = getEntryModule(compilation);
console.log('bbbbbbbbbbbb', entryModules);
for (const entryModule of entryModules) {
// Remove stale client references.
// entryModule.blocks = entryModule.blocks.filter(block =>
Expand All @@ -192,7 +180,6 @@ export class RspackRscClientPlugin {
// );
// }),
// );

if (entryModule) {
addClientReferencesChunks(compilation, entryModule, callback);
}
Expand Down Expand Up @@ -295,15 +282,6 @@ export class RspackRscClientPlugin {
? this.clientReferencesMap.get(resourcePath)
: undefined;

if (resourcePath?.includes('Counter')) {
console.log(
'clientReferences2222222222',
this.clientReferencesMap,
resourcePath,
clientReferences,
);
}

if (clientReferences) {
const moduleId = chunkGraph.getModuleId(module);

Expand All @@ -321,18 +299,12 @@ export class RspackRscClientPlugin {
chunksSet.add(chunk);
}

console.log(
'ccccccccccc',
chunkGraph.getModuleChunksIterable(module),
);

for (const connection of moduleGraph.getOutgoingConnections(
module,
)) {
for (const chunk of chunkGraph.getModuleChunksIterable(
connection.module,
)) {
console.log('aaaaaaaaaaaa');
chunksSet.add(chunk);
}
}
Expand Down
Loading

0 comments on commit 2253662

Please sign in to comment.