Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix HMR in static build + @import HMR #2440

Merged
merged 5 commits into from
Jan 24, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/angry-apricots-invite.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fixes HMR of CSS that is imported from astro, when using the static build flag
15 changes: 14 additions & 1 deletion packages/astro/src/core/ssr/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@ export async function render(renderers: Renderer[], mod: ComponentInstance, ssrO
if (!Component) throw new Error(`Expected an exported Astro component but received typeof ${typeof Component}`);
if (!Component.isAstroComponentFactory) throw new Error(`Unable to SSR non-Astro component (${route?.component})`);


// Add hoisted script tags
const scripts = astroConfig.buildOptions.experimentalStaticBuild
? new Set<SSRElement>(
Expand All @@ -229,6 +230,18 @@ export async function render(renderers: Renderer[], mod: ComponentInstance, ssrO
)
: new Set<SSRElement>();

// Inject HMR scripts
if(mode === 'development' && astroConfig.buildOptions.experimentalStaticBuild) {
matthewp marked this conversation as resolved.
Show resolved Hide resolved
scripts.add({
props: { type: 'module', src: '/@vite/client' },
children: '',
});
scripts.add({
props: { type: 'module', src: new URL('../../runtime/client/hmr.js', import.meta.url).pathname },
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn’t realize src is a file system path. TIL.

children: '',
});
}

const result = createResult({ astroConfig, logging, origin, params, pathname, renderers, scripts });
// Resolves specifiers in the inline hydrated scripts, such as "@astrojs/renderer-preact/client.js"
result.resolve = async (s: string) => {
Expand All @@ -249,7 +262,7 @@ export async function render(renderers: Renderer[], mod: ComponentInstance, ssrO
const tags: vite.HtmlTagDescriptor[] = [];

// dev only: inject Astro HMR client
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Should this comment be amended?

if (mode === 'development') {
if (mode === 'development' && !astroConfig.buildOptions.experimentalStaticBuild) {
tags.push({
tag: 'script',
attrs: { type: 'module' },
Expand Down
6 changes: 6 additions & 0 deletions packages/astro/src/vite-plugin-astro/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ async function compile(config: AstroConfig, filename: string, source: string, vi
experimentalStaticExtraction: config.buildOptions.experimentalStaticBuild,
// TODO add experimental flag here
preprocessStyle: async (value: string, attrs: Record<string, string>) => {
// When using this flag CSS because <link> and therefore goes through Vite's
// CSS pipeline. We don't need to transform here.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When using this flag CSS because and therefore...

I’m having trouble understanding this. Could it be written differently?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, i'll amend it.

if(config.buildOptions.experimentalStaticBuild) {
return { code: value };
}

const lang = `.${attrs?.lang || 'css'}`.toLowerCase();
try {
const result = await transformWithVite({
Expand Down
17 changes: 16 additions & 1 deletion packages/astro/src/vite-plugin-astro/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { AstroConfig } from '../@types/astro';
import type { LogOptions } from '../core/logger';

import esbuild from 'esbuild';
import npath from 'path';
import { fileURLToPath } from 'url';
import { AstroDevServer } from '../core/dev/index.js';
import { getViteTransform, TransformHook } from './styles.js';
Expand All @@ -29,6 +30,11 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu
}

let viteTransform: TransformHook;

// Variables for determing if an id starts with /src...
const srcRootWeb = config.src.pathname.slice(config.projectRoot.pathname.length - 1);
const isBrowserPath = (path: string) => path.startsWith(srcRootWeb);

return {
name: '@astrojs/vite-plugin-astro',
enforce: 'pre', // run transforms before other plugins can
Expand All @@ -38,7 +44,16 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu
// note: don’t claim .astro files with resolveId() — it prevents Vite from transpiling the final JS (import.meta.globEager, etc.)
async resolveId(id) {
// serve sub-part requests (*?astro) as virtual modules
if (parseAstroRequest(id).query.astro) {
const { query } = parseAstroRequest(id);
if (query.astro) {
// Convert /src/pages/index.astro?astro&type=style to /Users/name/
// Because this needs to be the id for the Vite CSS plugin to property resolve
// relative @imports.
if(query.type === 'style' && isBrowserPath(id)) {
const outId = npath.posix.join(config.projectRoot.pathname, id);
FredKSchott marked this conversation as resolved.
Show resolved Hide resolved
return outId;
}

return id;
}
},
Expand Down
11 changes: 9 additions & 2 deletions packages/astro/vendor/vite/dist/client/client.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,11 @@ function warnFailedFetch(err, path) {
socket.addEventListener('message', async ({ data }) => {
handleMessage(JSON.parse(data));
});
function cleanUrl(pathname) {
let url = new URL(pathname, location);
url.searchParams.delete('direct');
return url.pathname + url.search;
}
Comment on lines +207 to +211
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would you add /** comment */ above this to describe why it’s needed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remember that this is Vite built code and will change when/if we update. But yeah I can for now.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

let isFirstUpdate = true;
async function handleMessage(payload) {
switch (payload.type) {
Expand Down Expand Up @@ -230,11 +235,13 @@ async function handleMessage(payload) {
// css-update
// this is only sent when a css file referenced with <link> is updated
let { path, timestamp } = update;
path = path.replace(/\?.*/, '');
let searchUrl = cleanUrl(path);
// can't use querySelector with `[href*=]` here since the link may be
// using relative paths so we need to use link.href to grab the full
// URL for the include check.
const el = [].slice.call(document.querySelectorAll(`link`)).find((e) => e.href.includes(path));
const el = [].slice.call(document.querySelectorAll(`link`)).find((e) => {
return cleanUrl(e.href).includes(searchUrl)
});
if (el) {
const newPath = `${base}${path.slice(1)}${path.includes('?') ? '&' : '?'}t=${timestamp}`;
el.href = new URL(newPath, el.href).href;
Expand Down