From 981e2a839b5a0292513bf2009216250f2a8730eb Mon Sep 17 00:00:00 2001 From: "Fred K. Schott" Date: Mon, 21 Mar 2022 13:05:11 -0700 Subject: [PATCH] add injected scripts to markdown pages (#2848) * add injected scripts to markdown pages * Create twenty-kiwis-tease.md Co-authored-by: Nate Moore --- .changeset/twenty-kiwis-tease.md | 5 +++ .../astro/src/vite-plugin-markdown/index.ts | 32 +++++++++++++------ 2 files changed, 28 insertions(+), 9 deletions(-) create mode 100644 .changeset/twenty-kiwis-tease.md diff --git a/.changeset/twenty-kiwis-tease.md b/.changeset/twenty-kiwis-tease.md new file mode 100644 index 000000000..83f681a61 --- /dev/null +++ b/.changeset/twenty-kiwis-tease.md @@ -0,0 +1,5 @@ +--- +"astro": patch +--- + +add missing injected "page" scripts into markdown pages diff --git a/packages/astro/src/vite-plugin-markdown/index.ts b/packages/astro/src/vite-plugin-markdown/index.ts index ac4f48914..9ea41a842 100644 --- a/packages/astro/src/vite-plugin-markdown/index.ts +++ b/packages/astro/src/vite-plugin-markdown/index.ts @@ -1,17 +1,27 @@ -import type { Plugin } from 'vite'; -import type { AstroConfig } from '../@types/astro'; - +import { transform } from '@astrojs/compiler'; +import ancestor from 'common-ancestor-path'; import esbuild from 'esbuild'; import fs from 'fs'; -import { fileURLToPath } from 'url'; -import { transform } from '@astrojs/compiler'; +import type { Plugin } from 'vite'; +import type { AstroConfig } from '../@types/astro'; interface AstroPluginOptions { config: AstroConfig; } -/** Transform .astro files for Vite */ +// TODO: Clean up some of the shared logic between this Markdown plugin and the Astro plugin. +// Both end up connecting a `load()` hook to the Astro compiler, and share some copy-paste +// logic in how that is done. export default function markdown({ config }: AstroPluginOptions): Plugin { + function normalizeFilename(filename: string) { + if (filename.startsWith('/@fs')) { + filename = filename.slice('/@fs'.length); + } else if (filename.startsWith('/') && !ancestor(filename, config.projectRoot.pathname)) { + filename = new URL('.' + filename, config.projectRoot).pathname; + } + return filename; + } + return { name: 'astro:markdown', enforce: 'pre', // run transforms before other plugins can @@ -50,12 +60,16 @@ ${setup}`.trim(); astroResult = `${prelude}\n${astroResult}`; } - const filenameURL = new URL(`file://${id}`); - const pathname = filenameURL.pathname.substr(config.projectRoot.pathname.length - 1); + const filename = normalizeFilename(id); + const fileUrl = new URL(`file://${filename}`); + const isPage = filename.startsWith(config.pages.pathname); + if (isPage && config._ctx.scripts.some((s) => s.stage === 'page')) { + source += `\n