Skip to content

Commit

Permalink
fix: ve-plugin SSR + HMR
Browse files Browse the repository at this point in the history
  • Loading branch information
astahmer committed Dec 7, 2022
1 parent acaf592 commit 3490aca
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 21 deletions.
67 changes: 47 additions & 20 deletions ve-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,24 @@ const styleUpdateEvent = (fileId: string) =>

const virtualExtCss = ".vanilla.css";
const virtualExtJs = ".vanilla.js";
const virtualRE = /.vanilla.(css|js)$/;

interface Options {
export interface VanillaExtractPluginOptions {
identifiers?: IdentifierOption;
esbuildOptions?: CompileOptions["esbuildOptions"];
forceEmitCssInSsrBuild?: boolean;
}
export function vanillaExtractPlugin({
identifiers,
esbuildOptions,
}: Options = {}): Plugin {
forceEmitCssInSsrBuild: _forceEmitCssInSsrBuild,
}: VanillaExtractPluginOptions = {}): Plugin {
let config: ResolvedConfig;
let server: ViteDevServer;
const cssMap = new Map<string, string>();

let forceEmitCssInSsrBuild: boolean = !!process.env.VITE_RSC_BUILD || true;
let forceEmitCssInSsrBuild: boolean =
_forceEmitCssInSsrBuild || !!process.env.VITE_RSC_BUILD;
let packageName: string;

const getAbsoluteVirtualFileId = (source: string) =>
Expand Down Expand Up @@ -72,6 +76,30 @@ export function vanillaExtractPlugin({
forceEmitCssInSsrBuild = true;
}
},
// Re-parse .css.ts files when they change
async handleHotUpdate({ file, modules }) {
if (!cssFileFilter.test(file)) return;
try {
const virtuals: any[] = [];
const invalidate = (type: string) => {
const found = server.moduleGraph.getModulesByFile(`${file}${type}`);
found?.forEach((m) => {
virtuals.push(m);
return server.moduleGraph.invalidateModule(m);
});
};
invalidate(virtualExtCss);
invalidate(virtualExtJs);
// load new CSS
await server.ssrLoadModule(file);
return [...modules, ...virtuals];
} catch (e) {
// eslint-disable-next-line no-console
console.error(e);
throw e;
}
},
// Convert .vanilla.(js|css) URLs to their absolute version
resolveId(source) {
const [validId, query] = source.split("?");
if (!validId.endsWith(virtualExtCss) && !validId.endsWith(virtualExtJs)) {
Expand All @@ -87,18 +115,25 @@ export function vanillaExtractPlugin({
// There should always be an entry in the `cssMap` here.
// The only valid scenario for a missing one is if someone had written
// a file in their app using the .vanilla.js/.vanilla.css extension
if (cssMap.has(absoluteId)) {
// Keep the original query string for HMR.
return absoluteId + (query ? `?${query}` : "");
}
// Keep the original query string for HMR.
return absoluteId + (query ? `?${query}` : "");
},
load(id) {
// Provide virtual CSS content
async load(id) {
const [validId] = id.split("?");

if (!cssMap.has(validId)) {
if (!virtualRE.test(validId)) {
return;
}

if (!cssMap.has(validId)) {
// Try to parse the parent
const parentId = validId.replace(virtualRE, "");
await server.ssrLoadModule(parentId);
// Now we should have the CSS
if (!cssMap.has(validId)) return;
}

const css = cssMap.get(validId);

if (typeof css !== "string") {
Expand Down Expand Up @@ -174,27 +209,19 @@ export function vanillaExtractPlugin({
filePath: validId,
identOption,
serializeVirtualCssPath: async ({ fileScope, source }) => {
const buggyRootRelativeId = `${fileScope.filePath}${
config.command === "build" || (ssr && forceEmitCssInSsrBuild)
const rootRelativeId = `${fileScope.filePath}${
config.command === "build" || forceEmitCssInSsrBuild
? virtualExtCss
: virtualExtJs
}`;
const rootRelativeId = `${fileScope.filePath}${virtualExtCss}`;
const absoluteId = getAbsoluteVirtualFileId(rootRelativeId);
console.log({
rootRelativeId,
buggyRootRelativeId,
ssr,
forceEmitCssInSsrBuild,
command: config.command,
});

let cssSource = source;

if (
server &&
cssMap.has(absoluteId) &&
cssMap.get(absoluteId) !== source
cssMap.get(absoluteId) !== cssSource
) {
const { moduleGraph } = server;
const [module] = Array.from(
Expand Down
5 changes: 4 additions & 1 deletion vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ const config: UserConfig = {
Inspect(),
react(),
ssr({ includeAssetsImportedByServer: true }),
vanillaExtractPlugin({ identifiers: "debug" }),
vanillaExtractPlugin({
identifiers: "debug",
forceEmitCssInSsrBuild: true,
}),
],
};

Expand Down

0 comments on commit 3490aca

Please sign in to comment.