Code splitting with build-time macros #6928
-
|
I'm using file based routing (with vite) and trying out React Spectrum for UI. React Spectrum has a macro called style that provides an easy way to style UI components. The macro is imported like import { style } from '@react-spectrum/s2/style' with { type: 'macro' }and used in route files something like export const Route = createFileRoute('/about')({
component: AboutComponent,
});
function AboutComponent() {
return (
<div
className={style({
margin: 0,
padding: 4,
})}
>
<h4>About</h4>
</div>
);
}If I use automatic code splitting, the macro is only run at build time on the __root.tsx route. It is not run on other route files at build time which causes a runtime error when attempting to navigate due to node library calls (in the macro) not available in the browser. If I turn off automatic code splitting, it works fine. Is there a way to configure vite and/or code splitting to run the macros at build time before the route chunks are built? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
|
can you please provide a complete minimal reproducer project for this? |
Beta Was this translation helpful? Give feedback.
-
|
For what it's worth, while upgrading to TypeScript v6 and Vite v8, I noticed macros.vite() can return function parcelMacrosWithNormalizedIds() {
const plugin = macros.vite();
const plugins = Array.isArray(plugin) ? plugin : [plugin];
const normalizedPlugins = plugins.map((p) => ({
...p,
name: `${p.name}-normalized-ids`,
transform(code: string, id: string) {
return p.transform?.call(this, code, id.replace(/\?.*$/, ''));
},
}));
return normalizedPlugins;
}
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
const isProd = mode === 'production';
return {
plugins: [
// macros.vite(), // Must be first!
...parcelMacrosWithNormalizedIds(), // Must be first!
tanstackRouter({ target: 'react', autoCodeSplitting: isProd }), // Only split in production
react(),
],
//...
};TypeScript still complains about the |
Beta Was this translation helpful? Give feedback.
this fixes it and produces (AFAIK) the correct output: