Skip to content

Commit

Permalink
feat: support Compilation.namedChunks (#4255)
Browse files Browse the repository at this point in the history
  • Loading branch information
h-a-n-a authored Oct 8, 2023
1 parent 9bd940c commit 07249dd
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 0 deletions.
1 change: 1 addition & 0 deletions crates/node_binding/binding.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export class JsCompilation {
getAssetSource(name: string): JsCompatSource | null
getModules(): Array<JsModule>
getChunks(): Array<JsChunk>
getNamedChunk(name: string): JsChunk | null
/**
* Only available for those none Js and Css source,
* return true if set module source successfully, false if failed.
Expand Down
9 changes: 9 additions & 0 deletions crates/node_binding/src/js_values/compilation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,15 @@ impl JsCompilation {
.collect::<Vec<_>>()
}

#[napi]
pub fn get_named_chunk(&self, name: String) -> Option<JsChunk> {
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.
Expand Down
15 changes: 15 additions & 0 deletions packages/rspack/src/Compilation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, Readonly<JsChunk>> {
return {
get: (property: unknown) => {
if (typeof property === "string") {
return this.#inner.getNamedChunk(property) ?? undefined;
}
}
} as Map<string, Readonly<JsChunk>>;
}

/**
* Get the associated `modules` of an given chunk.
*
Expand Down
26 changes: 26 additions & 0 deletions packages/rspack/tests/Compiler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 07249dd

Please sign in to comment.