Skip to content

Commit

Permalink
Allow TypeScript in hoisted scripts (#3665)
Browse files Browse the repository at this point in the history
* Allow TypeScript in hoisted scripts

* Pass skipSelf

* Fix linting
  • Loading branch information
matthewp authored Jun 22, 2022
1 parent c2dffc1 commit 9a81326
Show file tree
Hide file tree
Showing 9 changed files with 76 additions and 19 deletions.
23 changes: 23 additions & 0 deletions .changeset/neat-seas-peel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
'astro': patch
---

Allow TypeScript inside script tags

This makes it so that you can use TypeScript inside of script tags like so:

```html
<script>
interface Person {
name: string;
}
const person: Person = {
name: 'Astro'
};
console.log(person);
</script>
```

Note that the the VSCode extension does not currently support this, however.
2 changes: 1 addition & 1 deletion packages/astro/src/core/build/vite-plugin-analyzer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export function vitePluginAnalyzer(
scan(this: PluginContext, scripts: AstroPluginMetadata['astro']['scripts'], from: string) {
const hoistedScripts = new Set<string>();
for (let i = 0; i < scripts.length; i++) {
const hid = `${from.replace('/@fs', '')}?astro&type=script&index=${i}`;
const hid = `${from.replace('/@fs', '')}?astro&type=script&index=${i}&lang.ts`;
hoistedScripts.add(hid);
}

Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/runtime/server/metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export class Metadata {

while (i < metadata.hoisted.length) {
// Strip off the leading "/@fs" added during compilation.
yield `${pathname.replace('/@fs', '')}?astro&type=script&index=${i}`;
yield `${pathname.replace('/@fs', '')}?astro&type=script&index=${i}&lang.ts`;
i++;
}
}
Expand Down
37 changes: 25 additions & 12 deletions packages/astro/src/vite-plugin-astro/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { PAGE_SCRIPT_ID, PAGE_SSR_SCRIPT_ID } from '../vite-plugin-scripts/index
import { getFileInfo } from '../vite-plugin-utils/index.js';
import { cachedCompilation, CompileProps } from './compile.js';
import { handleHotUpdate, trackCSSDependencies } from './hmr.js';
import { parseAstroRequest } from './query.js';
import { parseAstroRequest, ParsedRequestResult } from './query.js';
import { getViteTransform, TransformHook } from './styles.js';

const FRONTMATTER_PARSE_REGEXP = /^\-\-\-(.*)^\-\-\-/ms;
Expand Down Expand Up @@ -48,6 +48,16 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu
const srcRootWeb = config.srcDir.pathname.slice(config.root.pathname.length - 1);
const isBrowserPath = (path: string) => path.startsWith(srcRootWeb);

function resolveRelativeFromAstroParent(id: string, parsedFrom: ParsedRequestResult): string {
const filename = normalizeFilename(parsedFrom.filename);
const resolvedURL = new URL(id, `file://${filename}`);
const resolved = resolvedURL.pathname;
if (isBrowserPath(resolved)) {
return relativeToRoot(resolved + resolvedURL.search);
}
return slash(fileURLToPath(resolvedURL)) + resolvedURL.search;
}

return {
name: 'astro:build',
enforce: 'pre', // run transforms before other plugins can
Expand All @@ -59,19 +69,17 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu
viteDevServer = server;
},
// note: don’t claim .astro files with resolveId() — it prevents Vite from transpiling the final JS (import.meta.globEager, etc.)
async resolveId(id, from) {
async resolveId(id, from, opts) {
// If resolving from an astro subresource such as a hoisted script,
// we need to resolve relative paths ourselves.
if (from) {
const parsedFrom = parseAstroRequest(from);
if (parsedFrom.query.astro && isRelativePath(id) && parsedFrom.query.type === 'script') {
const filename = normalizeFilename(parsedFrom.filename);
const resolvedURL = new URL(id, `file://${filename}`);
const resolved = resolvedURL.pathname;
if (isBrowserPath(resolved)) {
return relativeToRoot(resolved + resolvedURL.search);
}
return slash(fileURLToPath(resolvedURL)) + resolvedURL.search;
const isAstroScript = parsedFrom.query.astro && parsedFrom.query.type === 'script';
if (isAstroScript && isRelativePath(id)) {
return this.resolve(resolveRelativeFromAstroParent(id, parsedFrom), from, {
custom: opts.custom,
skipSelf: true,
});
}
}

Expand Down Expand Up @@ -170,6 +178,11 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu
hoistedScript.type === 'inline'
? hoistedScript.code!
: `import "${hoistedScript.src!}";`,
meta: {
vite: {
lang: 'ts',
},
}
};
}
}
Expand Down Expand Up @@ -205,8 +218,8 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu

let i = 0;
while (i < transformResult.scripts.length) {
deps.add(`${id}?astro&type=script&index=${i}`);
SUFFIX += `import "${id}?astro&type=script&index=${i}";`;
deps.add(`${id}?astro&type=script&index=${i}&lang.ts`);
SUFFIX += `import "${id}?astro&type=script&index=${i}&lang.ts";`;
i++;
}

Expand Down
10 changes: 6 additions & 4 deletions packages/astro/src/vite-plugin-astro/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ export interface AstroQuery {
raw?: boolean;
}

export interface ParsedRequestResult {
filename: string;
query: AstroQuery;
};

// Parses an id to check if its an Astro request.
// CSS is imported like `import '/src/pages/index.astro?astro&type=style&index=0&lang.css';
// This parses those ids and returns an object representing what it found.
export function parseAstroRequest(id: string): {
filename: string;
query: AstroQuery;
} {
export function parseAstroRequest(id: string): ParsedRequestResult {
const [filename, rawQuery] = id.split(`?`, 2);
const query = Object.fromEntries(new URLSearchParams(rawQuery).entries()) as AstroQuery;
if (query.astro != null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
<script>
console.log('some content here.');
import '../scripts/some-files/one';
import '../scripts/some-files/two.js';

interface Props {
name: string;
}
const props: Props = { name: 'some string' };

console.log('some content here.', props);
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log('some-files/one');
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log('some-files/two');
9 changes: 9 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 9a81326

Please sign in to comment.