diff --git a/crates/node_binding/binding.d.ts b/crates/node_binding/binding.d.ts index 4eb70c19af1..0d465494fb5 100644 --- a/crates/node_binding/binding.d.ts +++ b/crates/node_binding/binding.d.ts @@ -15,6 +15,7 @@ export class JsCompilation { getAssetSource(name: string): JsCompatSource | null getModules(): Array getChunks(): Array + getNamedChunk(name: string): JsChunk | null /** * Only available for those none Js and Css source, * return true if set module source successfully, false if failed. diff --git a/crates/node_binding/src/js_values/compilation.rs b/crates/node_binding/src/js_values/compilation.rs index 0e92d8f3406..a1203c896c7 100644 --- a/crates/node_binding/src/js_values/compilation.rs +++ b/crates/node_binding/src/js_values/compilation.rs @@ -156,6 +156,15 @@ impl JsCompilation { .collect::>() } + #[napi] + pub fn get_named_chunk(&self, name: String) -> Option { + self + .inner + .named_chunks + .get(&name) + .and_then(|c| self.inner.chunk_by_ukey.get(c).map(JsChunk::from)) + } + #[napi] /// Only available for those none Js and Css source, /// return true if set module source successfully, false if failed. diff --git a/packages/rspack/src/Compilation.ts b/packages/rspack/src/Compilation.ts index cf7c13b003d..7ab3bb6456b 100644 --- a/packages/rspack/src/Compilation.ts +++ b/packages/rspack/src/Compilation.ts @@ -704,6 +704,21 @@ export class Compilation { return chunks; } + /** + * Get the named chunks. + * + * Note: This is a proxy for webpack internal API, only method `get` is supported now. + */ + get namedChunks(): Map> { + return { + get: (property: unknown) => { + if (typeof property === "string") { + return this.#inner.getNamedChunk(property) ?? undefined; + } + } + } as Map>; + } + /** * Get the associated `modules` of an given chunk. * diff --git a/packages/rspack/tests/Compiler.test.ts b/packages/rspack/tests/Compiler.test.ts index 53ae619c6d3..916a212bee0 100644 --- a/packages/rspack/tests/Compiler.test.ts +++ b/packages/rspack/tests/Compiler.test.ts @@ -1059,6 +1059,32 @@ describe("Compiler", () => { }); }); + it("should work with `namedChunks`", done => { + const mockFn = jest.fn(); + class MyPlugin { + apply(compiler: Compiler) { + compiler.hooks.afterCompile.tap("Plugin", compilation => { + let c = compilation.namedChunks.get("d"); + expect(c.name).toBe("d"); + mockFn(); + }); + } + } + const compiler = rspack({ + entry: { + d: "./d" + }, + context: path.join(__dirname, "fixtures"), + plugins: [new MyPlugin()] + }); + + compiler.build(error => { + expect(error).toBeFalsy(); + expect(mockFn).toBeCalled(); + done(); + }); + }); + it("should get assets with both `getAssets` and `assets`(getter)", done => { class MyPlugin { apply(compiler: Compiler) {