Skip to content

Commit

Permalink
fix(rspack-provider): react refresh not work in Micro front-end projects
Browse files Browse the repository at this point in the history
  • Loading branch information
9aoy committed Nov 30, 2023
1 parent 6200cf2 commit b569e41
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 2 deletions.
8 changes: 8 additions & 0 deletions .changeset/afraid-trains-leave.md
Original file line number Diff line number Diff line change
@@ -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 在微前端场景下不生效的问题
42 changes: 40 additions & 2 deletions packages/builder/builder-rspack-provider/src/plugins/react.ts
Original file line number Diff line number Diff line change
@@ -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',
Expand Down Expand Up @@ -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);
}
});
},
});
2 changes: 2 additions & 0 deletions packages/builder/builder-shared/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`;

Expand Down

0 comments on commit b569e41

Please sign in to comment.