fix(webpack): return proper webpack plugin from useLegacyNxPlugin function (#27340)

The current `useLegacyNxPlugin` has two issues:
1. It doesn't pass the configuration object, but rather the compiler
instance.
2. It doesn't handle async correctly

This PR resolves both issues.

<!-- If this is a particularly complex change or feature addition, you
can request a dedicated Nx release for this pull request branch. Mention
someone from the Nx team or the `@nrwl/nx-pipelines-reviewers` and they
will confirm if the PR warrants its own release for testing purposes,
and generate it for you if appropriate. -->

## Current Behavior
Legacy plugins don't actually work.

## Expected Behavior
Legacy plugins work.

## Related Issue(s)
<!-- Please link the issue being fixed so it gets closed when this is
merged. -->

Fixes #
This commit is contained in:
Jack Hsu 2024-08-08 11:29:55 -04:00 committed by GitHub
parent 6e8a3e51b4
commit 712dbbc2d5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,7 +1,7 @@
import { ExecutorContext, readCachedProjectGraph } from '@nx/devkit';
import { NxWebpackExecutionContext } from '../../utils/config';
import { NxAppWebpackPluginOptions } from '../nx-webpack-plugin/nx-app-webpack-plugin-options';
import { Configuration } from 'webpack';
import { type ExecutorContext, readCachedProjectGraph } from '@nx/devkit';
import type { NxWebpackExecutionContext } from '../../utils/config';
import type { NxAppWebpackPluginOptions } from '../nx-webpack-plugin/nx-app-webpack-plugin-options';
import type { Compiler, Configuration } from 'webpack';
import { normalizeOptions } from '../nx-webpack-plugin/lib/normalize-options';
/**
@ -57,12 +57,24 @@ export async function useLegacyNxPlugin(
};
const configuration = process.env.NX_TASK_TARGET_CONFIGURATION;
return async (config: Configuration) => {
const ctx: NxWebpackExecutionContext = {
context,
options: options as NxWebpackExecutionContext['options'],
configuration,
};
return await fn(config, ctx);
return {
apply(compiler: Compiler) {
compiler.hooks.beforeCompile.tapPromise('NxLegacyAsyncPlugin', () => {
return new Promise<void>((resolve) => {
fn(compiler.options as Configuration, ctx).then((updated) => {
// Merge options back shallowly since it's a fully functional configuration.
// Most likely, the user modified the config in place, but this guarantees that updates are applied if users did something like:
// `return { ...config, plugins: [...config.plugins, new MyPlugin()] }`
Object.assign(compiler.options, updated);
resolve();
});
});
});
},
};
}