Translated by AI model deepseek-flash.
Source Language: Simplified Chinese, Target Language: english, Translation Time: 2026-11-18 21:14
.AI translation is for reference only. Accuracy is not guaranteed, please refer to the original text.
Research task: task-1 | Environment: Windows 11 + Node v24.18.0 + pnpm 12.9.1 + astro 7.4.5 + vite 8.3.5 (rolldown-vite)
Evidence: actual testing in the root project (
astro sync/pnpm build/ dev all pass), isolated experiments inexperiments/astro7/**,node_modules/astro/dist/**source, Astro official docs (v7 docs are authoritative)Legend: [Verified] = confirmed by running or source code; [Inferred] = source-code inference, not directly verified by running.
Conclusion first: This approach is feasible on Astro 7.4.5, and has been implemented in the root project; the key constraints are that the glob base must be a POSIX path relative to config.root, the content repository
site.config.tsmay only use erasable TS syntax, and the custom mode switch must use environment variables rather than CLI arguments.
0. Conclusion at a Glance
| # | Question | Conclusion | Status |
|---|---|---|---|
| 1 | How to connect an external content directory | glob({ base: <POSIX path relative to project root> }) works; file() is only suitable for a single file; not usable across drive letters | [Verified] |
| 2 | Config loading / Node native TS | astro.config.mjs is loaded by Node native import(), so TLA / process.env / process.argv are all available; external .ts can be directly imported with Node 24 strip-types (except enum); defineConfig does not support an async factory | [Verified]/[Inferred] |
| 3 | vite.define in updateConfig | An integration calling updateConfig({vite:{define,...}}) in astro:config:setup will merge into the Vite config and take effect for src/content.config.ts; but it only performs static text replacement | [Verified] |
| 4 | virtual | The integration registers a Vite plugin (Astro 7 has no addVitePlugin), and it works in both dev/build; types need to be handwritten in env.d.ts | [Verified] |
| 5 | Unknown CLI arguments | yargs-parser silently accepts them without error; the --background child process only forwards whitelisted flags, so custom arguments are lost | [Verified] |
| 6 | dev --background | Built into 7.0+: astro dev --background/stop/status/logs; Windows does not automatically background it, so you must manually add the flag | [Verified] |
| 7 | Impact of dynamic site | sitemap/rss/canonical all only read config.site; just compute site correctly at the config stage, no code changes needed | [Verified/Source] |
| 8 | Official separation practice | There is no official "content repository" concept; both local/remote loaders are possible, and an external local directory is just glob(base) | [Verified/Docs] |
1. Content Sources: glob() / file() / Custom Loader
1.1 glob(): Reading Posts from Outside the Project Root [Verified]
// src/content.config.ts(根项目实际实现)
const blogBase = resolveBlogBase(); // 返回相对项目根的 POSIX 路径,如 '../content/posts'
export const collections = {
blog: defineCollection({
loader: glob({ base: blogBase, pattern: '**/*.{md,mdx}' }),
schema: ({ image }) => z.object({ title: z.string(), pubDate: z.coerce.date() }),
}),
};
- In the source,
baseis resolved asnew URL(base, config.root)(node_modules/astro/dist/content/loaders/glob.js:186), so it defaults to relative to the project root; you can also pass afile://URL or an absolute path (docs: string | URL). patterncannot start with/or../(glob.js:53,56throws "Glob patterns cannot start with ...", requiring use ofbaseinstead).- Files may be located outside the project root: internally it uses
posixRelative(config.root, filePath)(glob.js:110) to record them as../content/posts/x.md; the entry id is still relative to base;watcher.add(filePath)(glob.js:250) registers the watch. - Key Windows pitfall: do not pass a
C:\...\postsabsolute path string tobase(new URL('C:\...', root)will parse it as ac:scheme). The correct approach ispath.relative(rootDir, postsDir).split(path.sep).join('/'); whenpath.isAbsolute(relativePath)is true (across drives), there is no solution, and you must throw an error or change the approach. - Accessing files outside the project root under dev requires
vite.server.fs.allowto include the content repository directory (see §4).
1.2 file(): Single-File Collection [Verified/Source]
fileNameis likewisenew URL(fileName, config.root)and cannot contain*(otherwise FileGlobNotSupported); it supports JSON / YAML / TOML, or a custom parser viaoptions.parser.- Data must be either "an array of objects containing a unique id/slug" or "an id → entry object"; a missing file only logs logger.error and does not throw; no extension/no parser throws FileParserNotFound.
- Conclusion: suitable for scenarios where the content repository has only one data file (such as navigation/configuration), not suitable for post collections (no markdown rendering, no per-file schema metadata).
1.3 Custom Loader [Docs]
- The docs explicitly state that a loader can "load data from any source, local or remote"; remote content (CMS) requires a custom loader or community loader, and Astro 7 has no built-in remote loader.
- For simple scenarios, you can directly write an async function returning an array/object; for complex scenarios, use an object loader API to maintain store/id/digest/watch yourself.
- Recommendation: use
glob()for posts (both theme/content modes have been built and verified in the root project); do not use a loader for site configuration—directly importing.tsat the config stage is simpler (see §2).
2. Loading astro.config.mjs and Node 24 Native TS
2.1 Loading Mechanism [Verified/Source]
node_modules/astro/dist/core/config/vite-load.js:
- Path matches
/\.[cm]?js$/(.mjs/.js/.cjs) → Node nativeawait import(pathToFileURL(configPath) + '?t=' + Date.now())(:10), executed in the same process. - Others (.ts/.mts) → start a minimal Vite server and use
environment.runner.import(configPath)to execute in Vite SSR (:31-34). - That is: Astro does not use Vite's
loadConfigFromFile(configFile: falsein create-vite,core/create-vite.js), but implements its own ".mjs → Node native import / .ts → Vite runner". - Therefore: keep
astro.config.mjsto 100% guarantee top-level await,process.env,process.argv, Node native TS import, and other capabilities; although a.tsconfig generally also runs, its execution environment changes to the Vite runner, and behavior is controlled by Vite.
2.2 Top-Level Await and Async Factory [Verified]/[Inferred]
- TLA is available: the top level of the root project's
astro.config.mjshasconst context = await loadSiteContext(root), and bothastro sync/pnpm buildpass. defineConfigis a synchronous identity function:function defineConfig(config)(dist/config/index.js:5-7), and its type signature also only accepts an object.export default async () => ({...})is not supported [Inferred]: loadConfig directly takesmod.default, thenmergeConfigRecursively({...defaults}, userConfig)iterates withfor...in; a function has no enumerable own properties → the config is treated as an empty object; it will also report a type error.- When you need async, use TLA, not an async factory.
2.3 Content Repository site.config.ts Imported Directly with Node 24 [Verified]
- The root project's
scripts/site-config.mjsusesawait import(pathToFileURL(file).href)to load<content-repo>/site.config.ts, takesmod.default ?? mod.siteConfig ?? mod.themeSiteConfig, and validates it at the config stage (title/description/url validity, etc.). - Actual test of Node 24.18 strip-only type erasure (
experiments/astro7/_cache/ts-test/,node --input-type=module -e "await import('./x.ts')"):import typeerasure: OK;satisfies SiteConfig: OK; interface + ordinary const: OK.export enum Mode {}: SyntaxError: TypeScript enum is not supported in strip-only mode.
- Therefore, the writing constraints for the content repository's
site.config.tsare:- Only erasable syntax may be used:
interface/type/import type/satisfies/ ordinaryconst; do not useenum,namespace, or constructor parameter properties. - Type reuse can only use
import type(no runtime import is produced after compilation/erasure). If the content repository is not inside the theme repository directory, cross-repository relative paths are unstable → recommend "theme exports types + content repository copies/generates a type declaration" or a type-only reference published to a package (type-researcher's task-2 direction). - Avoid any runtime imports (including value imports): the content repository usually has no node_modules, so Node cannot resolve dependencies and will fail.
- Only erasable syntax may be used:
3. Scope of Integration updateConfig({ vite })
3.1 Merge Chain [Verified/Source]
astro:config:setupexecutes before the Vite server is created (dist/integrations/hooks.js:105 runHookConfigSetup);updateConfiginside the hook is implemented asmergeConfig(updatedConfig, newConfig)(hooks.js:168-174).dist/core/create-vite.js:332comments give the merge order: 1 common → 2 user vite → 3 integration config → 4 command config;:365-372callsvite.mergeConfigin sequence.- Therefore
updateConfig({ vite: { define, plugins, server: { fs: { allow } }, resolve: { alias } } })is all effective, and applies to all subsequent Vite-transformed modules (src/**,src/content.config.ts, virtual modules, astro environment runner). Vite's officialmergeConfigmerges/overrides define/alias at key level.
3.2 Can define Enter content.config.ts? Yes [Verified]
- Content config loading chain: dev prewarms
kickOffContentConfigLoad(dist/content/config-prewarm.js:14) →loadContentConfig(dist/content/utils.js:304) →environment.runner.import(configPathname)(:310); the environment isASTRO_VITE_ENVIRONMENT_NAMES.astro(types-generator.js:66), i.e. the{ astro: { dev: {} } }RunnableDevEnvironment registered atcreate-vite.js:315-317. - Isolated experiment
experiments/astro7/flags-test/: the integration in config doesupdateConfig({ vite: { define: { __PROBE_DEFINE__: JSON.stringify('define-ok') } } }), and the top level ofsrc/content.config.tsasserts__PROBE_DEFINE__ === 'define-ok'otherwise throws;astro syncandastro build --content fooboth exit 0, and the content loader executes normally → define takes effect before content.config loading. - Limitation: define is only compile-time text/expression replacement, and only matches literals appearing in the source (such as
import.meta.env.X, custom global identifiers); it cannot proxy runtimeprocess.env.Xreads.
3.3 Root Project Choice
- The integration in the root project's
astro.config.mjsexecutesupdateConfig({ vite: { plugins: [siteConfigPlugin()], server: { fs: { allow: devServerAllow } } } })in config; devServerAllow = [project root] + content repository directory (no duplication if inside the project). - Do not use
vite.defineto pass site configuration: virtual modules can pass objects, have types, and can watch files, which is better than define string replacement.
4. Virtual Module virtual
4.1 Registration Method (Astro 7 Has No addVitePlugin) [Verified]
// astro.config.mjs(根项目做法)
function siteConfigIntegration(context) {
return {
name: 'site-config',
hooks: {
'astro:config:setup': ({ updateConfig }) => {
updateConfig({ vite: { plugins: [siteConfigPlugin(context)], server: { fs: { allow } } } });
},
},
};
}
- Astro 7's
astro:config:setuphook has noaddVitePlugin(it is not in the hooks list in types/public/integrations.d.ts; actual calls report "addVitePlugin is not a function"), so you must useupdateConfig({ vite: { plugins } }).
4.2 Plugin Implementation and Dev Watch [Verified]
const ID = 'virtual:site-config'; const RESOLVED = '\0' + ID;
function siteConfigPlugin(context) {
return {
name: 'virtual-site-config',
resolveId(id) { if (id === ID) return RESOLVED; },
load(id) {
if (id !== RESOLVED) return;
this.addWatchFile(path.resolve(context.siteConfigFile)); // dev 下文件变更触发虚拟模块失效
return `export const contentSource = ${JSON.stringify(context.contentSource)};\n` +
`const siteConfig = ${JSON.stringify(context.siteConfig)};\nexport default siteConfig;`;
},
};
}
- Application side:
src/config/index.tsdoesimport siteConfig, { contentSource } from 'virtual:site-config';src/env.d.tswritesdeclare module 'virtual:site-config'for TS checking (pnpm checkpasses). - Actual test: the root project passes in both dev + build modes (theme 8 pages / content 6 pages, dev curl returns correct HTML); after building the isolated experiment
flags-test'svirtual:probe-config, dist/index.html containsvirtual=True define=True. - Variant:
loadreturnsexport * from '<absolute path>/content/site.config.ts'. [Inferred] dev/build is theoretically feasible (Vite will continue to resolve that absolute .ts path and go through esbuild/rolldown transform), but this environment only verified it up to the config stage inexperiments/astro7/dual-repo/theme(that nested project was stuck on a yaml issue and did not complete the build), end-to-end verification was not completed; and it introduces issues with tsconfig ownership for .ts files outside the project,server.fs.allow, and HMR boundaries → recommend runtime value inlining (JSON) (verified in the root project).
5. CLI Argument Behavior
5.1 Unknown Flags Silently Ignored [Verified]
- Parsing:
dist/cli/index.js:206-210yargs(argv, { boolean: ['global'], alias: { g: 'global' } }); unknown flags enterflagsas-is (yargs-parser does not validate by default); command parsing only checks whetherflags._[2]is in the whitelist (:3); an unknown command falls back to help. - Actual test:
astro build --content fooexits 0 and the build is normal; inastro.config.mjs,process.argv.slice(2)can see["build","--content","foo"](isolated experiment flags-test) → you can parse custom arguments yourself in the config. - There is no official API for "registering custom CLI flags";
dist/cli/flags.js:4-27 flagsToAstroInlineConfigonly maps 12 built-in flags (root/config/port/host/site/base/outDir/mode/verbose/silent/force/allowedHosts/json).
5.2 --root / --config [Verified/Source]
--rootspecifies the project root (used to find the config and resolve relative paths);--configis relative to the project root (dist/core/config/config.js:38-52, throws ConfigNotFound if not found).- Config search order: astro.config.mjs → .js → .ts → .mts (
config.js:21-26).
5.3 ⚠ Parameter Forwarding Whitelist in Background Mode (Important)
dist/cli/server.js:43-71 buildBackgroundArgsonly forwards: --port/--host/--config/--root/--allowed-hosts/--json/--mode/--site/--base/--out-dir/--verbose/--silent/--open.- Therefore in
astro dev --background --content foo,--content foowill not be passed to the background child process; custom mode switches must use environment variables (the root project usesCONTENT_REPO) or be written somewhere visible to the config. - Recommendation: environment-variable-driven (
CONTENT_REPO=content pnpm dev), with CLI arguments only as "front-end sugar": read argv in astro.config.mjs and convert it into the internal context, do not rely on it being passed into the background.
6. dev server background (Built into Astro 7)
- Usage:
astro dev --background;astro dev status,astro dev logs [--follow],astro dev stop(7.0+, docs cli-reference "Background dev server"; preview supported in 7.2.0+). - Status/log locations: lock file
<root>/.astro/dev.json(dist/core/dev/lockfile.js:10), logs<root>/.astro/dev.log(:16); additional--jsonoutputs machine-readable logs (7.0.0),--forcestops the old and starts a new one,--ignore-lockignores the lock. - stop flow: SIGTERM → wait 5s (
GRACEFUL_SHUTDOWN_TIMEOUT=5e3,:5) → SIGKILL (:175-183). - Windows note:
supportsAgentAutoBackgroundingindist/cli/agent.jsreturns false for win32 (comment: detached child processes remain in the agent's Windows Job Object and terminate with the agent, astro#18019) → on Windows it will not automatically background, so you must manually add--background, and the background process may still be killed when the agent session ends [Risk]. - Actual test: the root project's
.astro/dev.jsonexists (background: true, port: 4341), and after dev starts in both modes, curl returns correct HTML [Lead verified]. - agent environment smoke test suggestion:
astro dev --background --port <free port>→ poll.astro/dev.jsonorastro dev statusuntil ready → curlhttp://localhost:<port>/to verify expected HTML →astro dev logs --lines 50to check errors →astro dev stop; avoid competing for the port with an existing dev server (e.g. 4341), and note that on Windows a detached child process may end when the agent ends.
7. Impact of Dynamic site (sitemap / RSS / canonical)
sitecomes from thesitefield inastro.config.mjs; the root project sets it tocontext.siteConfig.urlat the config stage, so the two modes naturally get different sites.- canonical:
src/components/BaseHead.astronew URL(Astro.url.pathname, Astro.site)→<link rel="canonical">, OGog:url, and the RSS alternate link all change accordingly. Build output verified (dist/index.html canonical =https://example.com/). - @astrojs/sitemap@3.7.4: when
if (!config.site)it warns "The Sitemap integration requires thesiteastro.config option. Skipping." (dist/index.js);finalSiteUrl = new URL(config.base, config.site)(:60); page loc =new URL(fullPath, finalSiteUrl)(:67/75). → As long as config.site is correct, the output is automatically correct, with no code changes needed. - @astrojs/rss@4.0.19:
siteis a required URL (dist/index.js zod), andchannel.link/item.linkusecreateCanonicalURL(site, trailingSlash, ...)(:130/:143). The root project'ssrc/pages/rss.xml.jsusessite: context.site; when Astro.site is missing, rss() will directly error, so site must always have a value. - Switching modes changes site → the content layer detects "Astro config changed" and "Clearing content store", then re-syncs (Lead actual test); for build output, it is recommended to use different
--out-dirfor the two modes (e.g. dist / dist-content) or separate CI jobs to avoid overwriting each other (currently both default to dist). - Conclusion: sitemap/RSS/canonical require no dual-repository changes; the only requirement is that
siteinastro.config.mjsis computed correctly at the config stage.
8. Official "Content and Code Separation" Practice (v7 Docs)
- Docs: a loader can "load data from any source, local or remote" (content-loader-reference);
glob()"creates entries from directories of files from anywhere on the filesystem" (also applies outside the project root, with base);file()reads a single JSON/YAML/TOML; remote content has no built-in loader and requires a custom loader (build-time data pull or live loader); community loaders cover Obsidian/GitHub/Bluesky, etc. (content-collections guide). - There is no official "content repository" pattern; there are three separation levels:
- Same-repository
content/subdirectory (simplest, project-internal path); - External local directory +
glob({ base })(this approach); - Remote CMS + custom loader (not adopted this time).
- Same-repository
- Dual-repository convention (implemented in the root project): the theme repository holds code + schema + default site configuration; the content repository holds
posts/*.md(mdx)+site.config.ts(you may addpackage.jsonto improve Node loading determinism); switch via theCONTENT_REPOenvironment variable; the schema is always defined by the theme, ensuring content repository content matches theme types. - Doc sources: https://docs.astro.build/en/reference/content-loader-reference/ ; https://docs.astro.build/en/guides/content-collections/ ; https://docs.astro.build/en/reference/configuration-reference/ ; https://docs.astro.build/en/reference/integrations-reference/ ; https://docs.astro.build/en/reference/cli-reference/ ; https://docs.astro.build/en/guides/upgrade-to/v7/
9. Risks and Unverified Items
- Cross-drive: when
path.relativestill yields an absolute path (content repository on another drive), there is no solution; the root project explicitly throws; the approach requires the same drive (different directories are fine). process.cwd()vsconfig.root: the root project'ssrc/content.config.tsusesprocess.cwd()to resolve paths; when started from another cwd (e.g.astro --root, monorepo filter), it may be inconsistent; the more robust approach is to derive based onconfig.root/file URL [Risk, unverified].- dev watch outside the project directory: the glob loader will
watcher.addexternal files, but the reliability of chokidar/rolldown watching directories outside the project on Windows is unverified (the root project's dev runs in both modes, but no dedicated test of "editing external md hot update" was done). - Nested subproject experiment failure: for a nested minimal project without its own node_modules, during sync Vite 8 ModuleRunner inlines and executes the CJS
yamlfrom the root node_modules, reportingrequire is not defined(only triggered byastro/loaders; flags-test does not import loaders, so it is normal). The root project (with its own node_modules) is unaffected, do not conclude from this that the environment is unusable; experiments conclusions are subject to actual testing in the root project. - Node TS syntax: the content repository's
site.config.tscannot use enum/namespace/parameter properties; value imports depend on Node resolving paths/packages, and fail when the content repository has no node_modules. - Virtual module types handwritten: the module declaration in
src/env.d.tsmust remain consistent with the plugin load content; when out of sync,astro checkmay pass but runtime errors occur. - site changes clear the content store: this is expected behavior, but frequent mode switching causes repeated sync; the dist outputs of the two modes overwrite each other (need separate outDir).
- Windows agent background dev: manual
--backgroundworks, but the detached child process may terminate with the agent Job Object (astro#18019 comment); long-running dev requires the host to manage it itself. - The behavior of sitemap/RSS when "site is empty" has been confirmed by source (sitemap skips, rss throws); this approach's config.site always has a value, and the empty-site experiment was not actually run.
10. Reproduction and Evidence Index
- Implemented files in the root project:
astro.config.mjs(TLA + loadSiteContext + integration + virtual + sitemap/mdx/fonts),scripts/site-config.mjs(reads CONTENT_REPO → loads/validates external site.config.ts),src/content.config.ts(glob base resolution + schema),src/config/site.ts(SiteConfig type + default configuration),src/config/index.ts(virtual module consumption),src/env.d.ts(virtual module types). - Isolated experiments:
experiments/astro7/flags-test/(integration updateConfig define injection into content.config.ts + virtual + process.argv observation; run scriptsexperiments/astro7/_cache/flags-test.ps1,virtual-test.ps1);experiments/astro7/_cache/ts-test/(three Node 24 native TS import cases: only-types/satisfies/enum);experiments/astro7/_cache/{content-loader-reference,content-collections,configuration-reference,integrations-reference,cli-reference,upgrade-to-v7}.md(doc caches). - Source anchors (all under
node_modules/astro/dist/):config/index.js:5,core/config/vite-load.js:10,31,core/config/config.js:21,38,core/config/merge.js:9,content/loaders/glob.js:53,110,186,250,content/loaders/file.js,content/utils.js:304,482,content/types-generator.js:66,content/config-prewarm.js:14,integrations/hooks.js:105,168,core/create-vite.js:315,332,365,cli/index.js:3,206,cli/flags.js:4,cli/dev/index.js:69,cli/server.js:43,84,cli/agent.js,core/dev/lockfile.js:5,10,16,175,vite-plugin-environment/index.js:8,36. - Runtime verification commands (Windows, pwsh, workdir=project root):
node node_modules/astro/bin/astro.mjs sync;pnpm build;CONTENT_REPO=content pnpm build; afterastro dev --background,astro dev status/logs/stop.
11. Lead Final Implementation Addendum (2026-11-04 13, Before Delivery)
- Parameter scheme implemented: this template supports
--content/--content-repo[=DIR]/--theme; foreground argv parsing inastro.config.mjsis retained (directpnpm exec astro build --contentworks), and a wrapperscripts/astro.mjswas added (package.json's dev/build/preview/check all start through it), converting the same arguments into theCONTENT_REPOenvironment variable before spawning Astro. - Reason (corresponding to the CLI/background conclusions in §6): the parent process of
astro dev --backgrounddoes not load the user's astro config, andbuildBackgroundArgs()only forwards whitelisted arguments (node_modules/astro/dist/cli/server.js:43-71), then starts a detached child process with(server.js). So ifpnpm dev --content --backgroundonly relies on reading argv in the config, it will fall back to theme mode; after changing to an environment variable, both the parent process and the background child process can inherit it → [Verified] background dev log[site-config] 内容来源: content (CONTENT_REPO=content, 目录: content), pagelang="zh-CN". - Correction to a §6 smoke test suggestion: Astro 7 background dev on Windows only listens on IPv6
[::1]:4321(actualnetstat -ano), so curl must usehttp://localhost:4321; using127.0.0.1gives ECONNREFUSED. - [Verified] Foreground/background two-mode matrix:
pnpm dev --background(theme, 200,lang="en"),pnpm dev --content --background(content, 200,lang="zh-CN");pnpm build8 pages,pnpm build --content6 pages,CONTENT_REPO=content pnpm build --theme8 pages (--themepriority correct);astro dev stopstops normally.
12. Lead Addendum: Content Repository Pages and MDX Layout (2026-11-04 13)
- Requirement: research whether MDX in content/posts can import, and migrate standalone pages such as src/pages/*.{md,mdx} to the content repository content/pages.
- Source location of MDX automatic layout: @astrojs/mdx 8.1.2's default processor is satteri (node_modules/@astrojs/mdx/dist/index.js
let processor = configuredProcessor ?? satteri()); the actual injection is in@astrojs/markdown-satteri/dist/mdx/create-processor.js:98-117: whenresolvedFrontmatter.layoutexists, appendimport __astro_layout_component__ from <layout>to the compilation result, and makeexport default function MDXContent(props)wrap with__astro_layout_jsx__(__astro_layout_component__, {file,url,content:frontmatterContent,frontmatter:frontmatterContent,headings,commands,'server:root':true,children}). The layout specifier is handed to Vite for resolution based on the relative path of that mdx file (@astrojs/mdx/dist/vite-plugin-mdx.js:33-41transform, then resolved by Vite). Therefore .mdx in content collections also applies layout, and aliases can be used (this template uses@theme). - .md pages do not apply layout: the comment in
node_modules/astro/dist/vite-plugin-markdown/index.js:88-89explicitly states that layout only applies to Markdown pages and direct imports, not content collection entries; the implementation isconst layout = hasContentFlag(id, MARKDOWN_CONTENT_ENTRY_FLAG) ? undefined : frontmatter.layout;. .md pages in content collections still generate routes, but do not apply frontmatter.layout; use .mdx if layout is needed. - Layout receives raw frontmatter: the MDX layout props are {file,url,content,frontmatter,headings,'server',children}; frontmatter comes from raw YAML (date is a string, not schema's z.coerce.date()); the layout must normalize it with new Date() itself. The first build's
TypeError: date.toISOString is not a functioncame from this, and it has been fixed in PageLayout's dateValue. - Route design: add a pages collection (glob base switches with mode: theme
./src/content/pages, content<content-repo>/pages),src/pages/[...slug].astrouses getCollection('pages') to generate/<id>; because MDX already automatically wraps the layout, the route template only renders<Content />, avoiding a double layout. [Verified] class="date" appears only once in the output. - Import verification: in content/posts/mdx-showcase.mdx,
import { Span } from '@ui'and the relative pathimport RelativeSpan from '../../src/components/ui/Span.astro'both build and render components; content pages can also use @ui. @ui = src/components/ui/index.ts, @theme = src directory, provided simultaneously by vite.resolve.alias in astro.config.mjs and root tsconfig paths. - Validation numbers (2026-11-04, Node 24.18 / pnpm 12 / Astro 7.4.5): [Verified]
pnpm build(theme) 9 page(s) (new src/content/pages/welcome.mdx),pnpm build:content8 page(s) (including /playlist, /theme-layout),pnpm check26 files 0 errors/0 warnings/0 hints; dev content mode /playlist and /theme-layout both 200 and layout/date/comments placeholder/ui-span normal; background dev still only listens on IPv6, need http://localhost:4321. - Implemented files: astro.config.mjs (@theme alias), tsconfig.json (paths @theme/*), src/pages/[...slug].astro (only renders Content), src/layouts/PageLayout.astro (theme reusable layout), content/layouts/PageLayout.astro (content repository layout), content/pages/{playlist,theme-layout}.mdx, src/content/pages/welcome.mdx, src/components/ui/{Span.astro,index.ts}.
If you enjoyed this, leave a comment~