Skip to content

Commit

Permalink
Setup react aliases
Browse files Browse the repository at this point in the history
  • Loading branch information
valentinpalkovic committed Jul 31, 2024
1 parent 7028373 commit f1c719b
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 1 deletion.
47 changes: 46 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ type VitePluginOptions = {
function VitePlugin({ dir = process.cwd() }: VitePluginOptions = {}): Plugin[] {
const resolvedDir = resolve(dir);
const nextConfigResolver = Promise.withResolvers<NextConfigComplete>();
const isVitestEnv = process.env.VITEST === "true";

return [
{
Expand All @@ -48,7 +49,51 @@ function VitePlugin({ dir = process.cwd() }: VitePluginOptions = {}): Plugin[] {
await loadConfig.default(phase, resolvedDir),
);

return config;
return {
...(!isVitestEnv && {
resolve: {
alias: {
react: "next/dist/compiled/react",
"react-dom": "next/dist/compiled/react-dom",
},
},
}),
test: {
alias: {
"react/jsx-dev-runtime": require.resolve(
"next/dist/compiled/react/jsx-dev-runtime.js",
),
"react/jsx-runtime": require.resolve(
"next/dist/compiled/react/jsx-runtime.js",
),

react: require.resolve("next/dist/compiled/react"),

"react-dom/test-utils": require.resolve(
"next/dist/compiled/react-dom/cjs/react-dom-test-utils.production.js",
),

"react-dom/cjs/react-dom.development.js": require.resolve(
"next/dist/compiled/react-dom/cjs/react-dom.development.js",
),

"react-dom/client": require.resolve(
"next/dist/compiled/react-dom/client.js",
),

"react-dom": require.resolve("next/dist/compiled/react-dom"),
},
},
};
},
configResolved(config) {
if (!config.test?.browser?.enabled) {
// biome-ignore lint/style/noNonNullAssertion: test is available in the config
config.test!.setupFiles = [
require.resolve("./mocks/storybook.global.js"),
...(config.test?.setupFiles ?? []),
];
}
},
},
vitePluginNextFont(),
Expand Down
11 changes: 11 additions & 0 deletions src/mocks/storybook.global.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// @ts-ignore no types
import moduleAlias from "module-alias";

// I only need this in non-browser mode
moduleAlias.addAliases({
react: "next/dist/compiled/react",
"react-dom/test-utils": require.resolve(
"next/dist/compiled/react-dom/cjs/react-dom-test-utils.production.js",
),
"react-dom": "next/dist/compiled/react-dom",
});
1 change: 1 addition & 0 deletions tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export default defineConfig({
"src/plugins/next-mocks/alias/navigation/index.ts",
"src/plugins/next-mocks/alias/router/index.ts",
"src/plugins/next-mocks/alias/rsc/server-only.ts",
"src/mocks/storybook.global.ts",
],
splitting: false,
clean: true,
Expand Down

0 comments on commit f1c719b

Please sign in to comment.