0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-01-27 22:19:04 -05:00

Support import astro components with vite queries (#11478)

This commit is contained in:
Bjorn Lu 2024-07-17 22:57:10 +08:00 committed by GitHub
parent 48d926c27e
commit 3161b6789c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 37 additions and 1 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
Supports importing Astro components with Vite queries, like `?url`, `?raw`, and `?direct`

View file

@ -9,7 +9,7 @@ import type {
} from './types.js';
import { normalizePath } from 'vite';
import { normalizeFilename } from '../vite-plugin-utils/index.js';
import { hasSpecialQueries, normalizeFilename } from '../vite-plugin-utils/index.js';
import { type CompileAstroResult, compileAstro } from './compile.js';
import { handleHotUpdate } from './hmr.js';
import { parseAstroRequest } from './query.js';
@ -200,6 +200,8 @@ export default function astro({ settings, logger }: AstroPluginOptions): vite.Pl
}
},
async transform(source, id) {
if (hasSpecialQueries(id)) return;
const parsedId = parseAstroRequest(id);
// ignore astro file sub-requests, e.g. Foo.astro?astro&type=script&index=0&lang.ts
if (!parsedId.filename.endsWith('.astro') || parsedId.query.astro) {

View file

@ -50,3 +50,12 @@ const postfixRE = /[?#].*$/s;
export function cleanUrl(url: string): string {
return url.replace(postfixRE, '');
}
const specialQueriesRE = /(?:\?|&)(?:url|raw|direct)(?:&|$)/;
/**
* Detect `?url`, `?raw`, and `?direct`, in which case we usually want to skip
* transforming any code with this queries as Vite will handle it directly.
*/
export function hasSpecialQueries(id: string): boolean {
return specialQueriesRE.test(id);
}

View file

@ -159,6 +159,12 @@ describe('Astro basic build', () => {
assert.equal($('h1').text(), 'WORKS');
});
it('Handles importing .astro?raw correctly', async () => {
const html = await fixture.readFile('/import-queries/raw/index.html');
const $ = cheerio.load(html);
assert.equal($('.raw-value').text(), '<h1>Hello</h1>\n');
});
describe('preview', () => {
it('returns 200 for valid URLs', async () => {
const result = await fixture.fetch('/');
@ -211,4 +217,12 @@ describe('Astro basic development', () => {
html.includes('<meta charset="utf-8">');
assert.ok(isUtf8);
});
it('Handles importing .astro?raw correctly', async () => {
const res = await fixture.fetch('/import-queries/raw/index.html');
assert.equal(res.status, 200);
const html = await res.text();
const $ = cheerio.load(html);
assert.equal($('.raw-value').text(), '<h1>Hello</h1>\n');
});
});

View file

@ -0,0 +1 @@
<h1>Hello</h1>

View file

@ -0,0 +1,5 @@
---
import contentStr from './_content.astro?raw';
---
<div class="raw-value">{contentStr}</div>