VS Code Astro Cheat Sheet
Sidebar
Programming · VS Code Astro Cheat Sheet
The Astro extension's settings and commands, plus the .astro component syntax, config options and command line. Checked against extension 2.16.20 installed here and the current Astro documentation. Sheet 19 in the VS Code series.
The Extension
Extension IDastro-build.astro-vscode (version 2.16.20 here): language support for .astro filesFeaturesHighlighting, errors, completions with auto-imports, Emmet in HTML/CSS, props completion for React/Vue/Svelte components, formatting, hover, go to definition, inlay hints, foldingFormattingUses Prettier with prettier-plugin-astro; outside the editor, install that plugin yourselfTypeScript pluginAlso lets .ts and .js files import and export Astro componentsSnippetspage_html (page with full HTML), page_layout (page using a layout), componentAstro: Reload ProjectsCommand Palette: re-read the project after changing config or adding filesAstro: Find File ReferencesCommand Palette: find where a file is importedAstro: Select TypeScript Version…Command Palette: choose the workspace or the bundled TypeScriptAstro: Open TypeScript configCommand Palette: open the tsconfig.json that appliesExtension Settings (astro.*)
astro.auto-import-cache.enabledFaster auto-imports; may miss brand-new files until reloaded (default true)astro.updateImportsOnFileMove.enabledUpdate imports when you move a file (default false)astro.content-intellisenseExperimental content collection completions in Markdown, MDX and Markdoc (default false)astro.language-server.ls-pathUse a specific language server executable (default none; rarely needed)astro.language-server.runtimePath to the Node program that runs the language server (default none)astro.trace.serveroff (default), messages, verbose: log language server trafficRelated VS Code Settings
typescript.inlayHints.*Astro is TypeScript-only, so set the typescript. versions, e.g. { "typescript.inlayHints.parameterNames.enabled": "all" }html.* / css.*HTML and CSS behaviour inside .astro files follows the html and css settings[astro]A settings.json language block for overrides that apply only to .astro fileseditor.defaultFormatterFor Astro files, usually "astro-build.astro-vscode" inside [astro] (or Prettier with the Astro plugin)tailwindCSS.includeLanguagesOnly if Tailwind class suggestions do not appear: { "astro": "html" }eslint.probeAlready includes astro; ESLint needs an Astro plugin to lint the templateComponent Syntax (.astro file)
--- … ---The frontmatter fence: JavaScript/TypeScript at the top that runs on the server when the page is built{expression}Insert a value or run an expression in the template, e.g. {title} or {items.map(i => <li>{i}</li>)}{cond && <p>…</p>}Conditional output; ternaries work tooclass={name}Dynamic attributes use curly braces<Fragment> or <> … </>Group elements without a wrapper element<slot />Where a parent's child content goes<slot name="sidebar" />A named slot; the parent fills it with slot="sidebar"const { title } = Astro.props;Read the props passed to the componentDifferences from JSXUse class, not className; several root elements are fine; HTML comments appear in the output, {/* */} comments do notThe Astro Object
Astro.propsProps passed in by the parentAstro.urlThe current page's URLAstro.paramsRoute parameters of a dynamic routeAstro.requestThe full request objectAstro.redirect(path)Send the visitor elsewhere (server rendering)Astro.slotshas() and render() for working with slot contentAstro.selfRefer to the component itself, for recursionTemplate Directives
set:html={string}Insert a string as raw HTML (only with content you trust)set:text={string}Insert a string as plain textclass:list={[…]}Build a class list from strings, objects and arraysdefine:vars={{ x }}Pass server values into a <style> as CSS variablesis:globalOn <style>: not scoped to the componentis:inline / is:rawLeave a script or style as written / do not process the contentclient:load client:idle client:visibleHydrate a framework component immediately / when idle / when it scrolls into viewclient:media="(min-width: 768px)"Hydrate when a media query matchesclient:only="react"Skip server rendering; render only in the browsertransition:name transition:animateView transitions for page changesProject Layout & Routing (my knowledge)
src/pages/Every .astro, .md or .html file here becomes a URL[slug].astroA dynamic route; in static builds it exports getStaticPaths()[...slug].astroA catch-all route that matches any depth of pathsrc/layouts/ and src/components/Reusable page frames and building blockssrc/content/Content collections: files with a typed schemapublic/Copied to the output as they are, with no processingdist/Where astro build writes the finished site.astro/types.d.tsTypes generated by astro sync; list it in tsconfig.json includetsconfig.jsonUsually extends astro/tsconfigs/strict (base and strictest also exist)astro.config.mjs
export default defineConfig({ … })The file shape; defineConfig comes from astro/configsiteYour final URL, used for canonical links and sitemapsbaseA sub-path the site is deployed underoutputstatic (default) or servertrailingSlashalways, never, ignore (default)build.formatdirectory (default), file, preserve: how pages become filesbuild.assetsFolder name for built assets (default _astro)srcDir / publicDir / outDirDefaults ./src, ./public, ./distintegrationsArray of integrations such as React, MDX or sitemap (default [])redirectsMap old paths to new ones: { "/old": "/new" }server.port / server.host / server.openDev server options (defaults 4321, false, false)devToolbar.enabledThe in-browser dev toolbar (default true)compressHTML / scopedStyleStrategyWhitespace handling / how component styles are scoped (default attribute)vitePass options through to ViteCommand Line (npx astro …)
devStart the dev server with hot reloading (port 4321 by default)buildBuild the site into dist/previewServe the built dist/ folder locallycheckType-check and report diagnostics (exits with code 1 on errors)syncGenerate TypeScript types for Astro modulesadd nameInstall and configure an integration, e.g. astro add reactinfoPrint your environment details (useful in bug reports)--port --host --openDev/preview flags: port number, network address, open the browser--config --root --site --basePoint at a different config, root, site URL or base path--force --verbose --silentClear the content cache / more logging / no loggingA Reasonable Starter Set (my suggestions, not defaults)
"typescript.inlayHints.parameterNames.enabled": "literals"Light-touch inlay hints in the frontmatter"[astro]": { "editor.defaultFormatter": "astro-build.astro-vscode" }Explicit formatter for Astro files"astro.updateImportsOnFileMove.enabled": trueImports follow the file when you move it (try it, then see whether you like it)"emmet.includeLanguages": { "astro": "html" }Only if Emmet abbreviations do not expand in .astro filesNo types, no completions or red errors that make no sense in .astro files
1) Run npx astro sync to regenerate the types, and make sure .astro/types.d.ts is in the include list of tsconfig.json. 2) Run Astro: Reload Projects. 3) Run Astro: Select TypeScript Version… and pick the workspace version if your project has its own. 4) Run TypeScript: Restart TS Server. 5) For a brand-new file that auto-import cannot find, reload the window or turn off astro.auto-import-cache.enabled.
Formatting .astro files with Prettier
Inside VS Code the extension formats .astro files for you. For the command line or CI, install prettier-plugin-astro and list it in the Prettier config: { "plugins": ["prettier-plugin-astro"], "overrides": [{ "files": "*.astro", "options": { "parser": "astro" } }] }. See the Prettier cheat sheet for the other options.