diff --git a/.changeset/afraid-trains-leave.md b/.changeset/afraid-trains-leave.md new file mode 100644 index 000000000000..9a736cf0d8c2 --- /dev/null +++ b/.changeset/afraid-trains-leave.md @@ -0,0 +1,8 @@ +--- +'@modern-js/builder-rspack-provider': patch +'@modern-js/builder-shared': patch +--- + +fix(rspack-provider): react refresh not work in Micro front-end projects + +fix(rspack-provider): 修复 react refresh 在微前端场景下不生效的问题 diff --git a/packages/builder/builder-rspack-provider/src/plugins/react.ts b/packages/builder/builder-rspack-provider/src/plugins/react.ts index d9fd74458c78..2a14b6faa8c0 100644 --- a/packages/builder/builder-rspack-provider/src/plugins/react.ts +++ b/packages/builder/builder-rspack-provider/src/plugins/react.ts @@ -1,5 +1,29 @@ -import type { BuilderPlugin } from '../types'; -import { setConfig, isUsingHMR } from '@modern-js/builder-shared'; +import type { BuilderPlugin, Rspack } from '../types'; +import { + setConfig, + isUsingHMR, + isClientCompiler, + isProd, +} from '@modern-js/builder-shared'; + +// Not needed in Rsbuild +const setupCompiler = (compiler: Rspack.Compiler) => { + if (!isClientCompiler(compiler)) { + return; + } + + // fix react refresh not work in Micro front-end projects when use legacy transformByDefault + // https://github.com/web-infra-dev/rspack/pull/4628/files#diff-81b3afbbf84bc30f7332fb7bd43d52a4544ae16190d41b4b0fe8e8d4c9ca89e0R59 + const definedModules = { + // For Mutiple Instance Mode + __react_refresh_library__: JSON.stringify( + compiler.webpack.Template.toIdentifier( + compiler.options.output.uniqueName || compiler.options.output.library, + ), + ), + }; + new compiler.webpack.DefinePlugin(definedModules).apply(compiler); +}; export const builderPluginReact = (): BuilderPlugin => ({ name: 'builder-plugin-react', @@ -35,5 +59,19 @@ export const builderPluginReact = (): BuilderPlugin => ({ ]); } }); + + api.onAfterCreateCompiler(({ compiler: multiCompiler }) => { + if (isProd()) { + return; + } + + if ((multiCompiler as Rspack.MultiCompiler).compilers) { + (multiCompiler as Rspack.MultiCompiler).compilers.forEach( + setupCompiler, + ); + } else { + setupCompiler(multiCompiler as Rspack.Compiler); + } + }); }, }); diff --git a/packages/builder/builder-shared/src/utils.ts b/packages/builder/builder-shared/src/utils.ts index e76f664087d4..02ec5dc9b6de 100644 --- a/packages/builder/builder-shared/src/utils.ts +++ b/packages/builder/builder-shared/src/utils.ts @@ -5,6 +5,8 @@ import type { } from './types'; import { join } from 'path'; +export const isProd = (): boolean => process.env.NODE_ENV === 'production'; + export const createVirtualModule = (content: string) => `data:text/javascript,${content}`;