Skip to content

Commit

Permalink
more robust way of determining where a chunk belongs (#64)
Browse files Browse the repository at this point in the history
  • Loading branch information
Zn4rK authored Oct 20, 2024
1 parent bf6afc9 commit cafa840
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/unlucky-humans-leave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@navita/vite-plugin': patch
---

Use options to determine if chunk belongs in server or client build
1 change: 1 addition & 0 deletions examples/with-remix/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"dev": "remix vite:dev --force",
"lint": "eslint --ignore-path .gitignore --cache --cache-location ./node_modules/.cache/eslint .",
"start": "remix-serve ./build/server/index.js",
"preview": "remix vite:build && remix-serve ./build/server/index.js",
"typecheck": "tsc"
},
"dependencies": {
Expand Down
15 changes: 10 additions & 5 deletions packages/vite-plugin/src/remix.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ let cssFileName: string;

export function navitaRemix(options?: Options): Plugin[] {
let isProduction = false;
let hasEmittedCss = false;

const { renderChunk, ...navitaVite } = navita(options);

Expand All @@ -25,8 +26,11 @@ export function navitaRemix(options?: Options): Plugin[] {

return `${code}\n${remixServerBuildExtension}`;
},
renderChunk(_, chunk) {
if (chunk.name === "root") {
renderChunk(_, chunk, options) {
const isServerChunk = options.dir.endsWith('/server');
const isClientChunk = options.dir.endsWith('/client');

if (isClientChunk && chunk.name === "root") {
// Generate a random name for the CSS file.
// Vite uses a file hash as the name, but since the client build will finish before
// the server build, we need to generate a random name for the CSS file.
Expand All @@ -39,12 +43,11 @@ export function navitaRemix(options?: Options): Plugin[] {

cssFileName = `assets/navita-${random}.css`;

// Attach the file to the root chunk so that it's included in the client build.
chunk.viteMetadata?.importedCss.add(cssFileName);
chunk.viteMetadata.importedCss.add(cssFileName);
return;
}

if (chunk.name === 'server-build') {
if (isServerChunk && !hasEmittedCss) {
// In the server-build, we'll generate the CSS and emit it as an asset.
// Remix will then move it to the client assets.
this.emitFile({
Expand All @@ -53,6 +56,8 @@ export function navitaRemix(options?: Options): Plugin[] {
type: 'asset',
source: getRenderer()?.engine.renderCssToString(),
});

hasEmittedCss = true;
}
},
}
Expand Down

0 comments on commit cafa840

Please sign in to comment.