wasm-pack-plugin icon indicating copy to clipboard operation
wasm-pack-plugin copied to clipboard

Feature: Hook to PostProcess package.json files emitted by wasm-pack

Open fbartho opened this issue 8 months ago • 0 comments

It'd be great if you could configure a hook into the plugin so that once the package.json is generated, that you could inject or otherwise adjust details about the exposed package.json without needing to use an external post-processing script.

I made a workaround as a webpack plugin -- but that's only marginally better than an external script. -- This could be used as an example on how to integrate it into wasm-pack-plugin, but consumers of wasm-pack-plugin shouldn't have to deal with that.
/** Lets you mess with an asset that might have been emitted by an external build tool */
class PatchPostBuildPlugin {
	private paths: string[];
	private handler: (filePath: string, contents: string) => string;

	constructor({
		paths,
		handler,
	}: {
		paths: string[];
		handler: (filePath: string, contents: string) => string;
	}) {
		this.paths = paths;
		this.handler = handler;
	}
	apply(compiler: webpack.Compiler) {
		const pluginName = PatchPostBuildPlugin.name;

		compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
			compilation.hooks.processAssets.tapPromise(
				{
					name: pluginName,
					stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
				},
				async (_assets) => {
					const work = this.paths.map(async (assetPath) => {
						const assetContents = await fs.promises.readFile(assetPath, "utf-8");
						const updatedContents = this.handler(assetPath, assetContents);
						compilation.emitAsset(assetPath, new webpack.sources.RawSource(updatedContents));
					});
					await Promise.all(work);
				},
			);
		});
	}
}

Semi-related feature request that got side-tracked with a CLI request that had a different solution: https://github.com/rustwasm/wasm-pack/issues/427

fbartho avatar Apr 22 '25 01:04 fbartho