### Astro File Example Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md An example Astro file demonstrating frontmatter and template markup. ```astro --- const message="Hello" const items=["a","b","c"] ---
` tag.
- `isTextNodeStartingWithWhitespace(node)`: Check starting whitespace.
- `isTextNodeEndingWithWhitespace(node)`: Check ending whitespace.
- `isTextNodeStartingWithLinebreak(node, nrLines)`: Check starting linebreak.
- `getUnencodedText(node)`: Get text content.
- `printRaw(node, strip)`: Serialize node.
- `startsWithLinebreak(text, nrLines)`: Check text start.
- `endsWithLinebreak(text, nrLines)`: Check text end.
- `shouldHugStart(node, opts)`: Format decision.
- `shouldHugEnd(node, opts)`: Format decision.
- `canOmitSoftlineBeforeClosingTag(path, opts)`: Format decision.
- `trimTextNodeLeft(node)`: Trim left side.
- `trimTextNodeRight(node)`: Trim right side.
- `printClassNames(value)`: Format class attribute.
- `manualDedent(input)`: Remove indentation, returns `{tabSize, char, result}`.
- `getSiblings(path)`: Get sibling nodes.
- `getNextNode(path)`: Get next sibling.
- `hasSetDirectives(node)`: Check for set:* directives.
- `getPreferredQuote(content, preferred)`: Select quote character, returns `QuoteResult`.
- `inferParserByTypeAttribute(type)`: Infer parser from type, returns `BuiltInParserName`.
```
--------------------------------
### Programmatic API for Formatting Astro Code
Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md
Demonstrates how to use the Prettier programmatic API to format Astro code, specifically with the 'astroSkipFrontmatter' option set to true.
```typescript
import prettier from 'prettier';
import astroPlugin from 'prettier-plugin-astro';
// Format with frontmatter skipped
const formatted = await prettier.format(code, {
parser: 'astro',
plugins: [astroPlugin],
astroSkipFrontmatter: true,
});
```
--------------------------------
### Configure Prettier Plugins in package.json
Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md
An alternative method to configure Prettier plugins and options by specifying them within the 'prettier' field in your package.json file. This approach is less recommended than using a dedicated config file.
```json
{
"prettier": {
"plugins": ["prettier-plugin-astro"],
"astroAllowShorthand": false,
"astroSkipFrontmatter": false,
"printWidth": 100,
"tabWidth": 2
}
}
```
--------------------------------
### Attribute Handling and Formatting
Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/architecture.md
Categorizes different types of attributes (empty, quoted, expression, shorthand, spread, template-literal) and illustrates how they are formatted, including the option for a single attribute per line.
```text
Attribute kinds and formatting:
empty:
quoted:
expression: (via embed)
shorthand: (when astroAllowShorthand=true)
spread:
template-literal:
Single attribute per line (when singleAttributePerLine=true):
```
--------------------------------
### Dynamic HTML Rendering with .map()
Source: https://github.com/withastro/prettier-plugin-astro/blob/main/test/fixtures/markdown/embedded-in-markdown/output.md
Render dynamic lists of HTML elements by using JavaScript's .map() function within the template to iterate over arrays.
```astro
---
const items = ["Dog", "Cat", "Platipus"];
---
{items.map((item) => - {item}
)}
```
--------------------------------
### Astro Plugin Options Definition
Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/index.md
TypeScript definition for plugin-specific configuration options. It maps option keys to their support metadata.
```typescript
export const options: Record
```
--------------------------------
### Scoped CSS in an Astro Component
Source: https://github.com/withastro/prettier-plugin-astro/blob/main/test/fixtures/markdown/embedded-in-markdown/output.md
Shows how to use a `
```
--------------------------------
### Plugin Options Interface
Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/types.md
Defines Astro-specific configuration options for Prettier. Use this interface to type partial options when configuring the plugin.
```typescript
interface PluginOptions {
astroAllowShorthand: boolean;
astroSkipFrontmatter: boolean;
}
```
--------------------------------
### Format with astroAllowShorthand enabled programmatically
Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md
Format code with attribute shorthand enabled using the Prettier programmatic API.
```typescript
import prettier from 'prettier';
import astroPlugin from 'prettier-plugin-astro';
// Format with shorthand enabled
const formatted = await prettier.format(code, {
parser: 'astro',
plugins: [astroPlugin],
astroAllowShorthand: true,
});
```
--------------------------------
### Astro AST Node Type Hierarchy
Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/types.md
Illustrates the hierarchical relationships between different Abstract Syntax Tree (AST) node types in Astro. This helps understand how various parts of an Astro file are represented.
```plaintext
Node (base)
├── RootNode (has children)
├── TextNode
├── CommentNode
├── DoctypeNode
├── ExpressionNode
├── AttributeNode
├── TagLikeNode (base for tag-like)
│ ├── ElementNode (has children, attributes)
│ ├── ComponentNode (has children, attributes)
│ ├── CustomElementNode (has children, attributes)
│ └── FragmentNode (has children, attributes)
└── FrontmatterNode
```
--------------------------------
### Runtime Dependencies for Prettier Plugin Astro
Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-summary.md
Lists the core runtime dependencies required for the Prettier plugin Astro to function, including the Astro compiler and Prettier itself.
```json
{
"@astrojs/compiler": "^2.9.1",
"prettier": "^3.5.3",
"sass-formatter": "^0.7.6"
}
```
--------------------------------
### Plugin Options Interface
Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/README.md
Defines the configuration options specific to the prettier-plugin-astro, including options for enabling shorthand attributes and skipping frontmatter formatting.
```typescript
interface PluginOptions {
astroAllowShorthand: boolean; // default: false
astroSkipFrontmatter: boolean; // default: false
}
```
--------------------------------
### Define and Use Component Props in Astro
Source: https://github.com/withastro/prettier-plugin-astro/blob/main/test/fixtures/markdown/embedded-in-markdown/input.md
Access component props using `Astro.props` in the frontmatter script. Destructure props to set default values for optional props.
```astro
---
// Example:
const { greeting = 'Hello', name } = Astro.props;
---
{greeting}, {name}!
```
--------------------------------
### Configure Prettier for Astro with External JavaScript Formatters
Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/configuration.md
Use this configuration in your .prettierrc.mjs file to enable the Prettier Astro plugin and skip formatting JavaScript frontmatter. It also sets standard Prettier options for the template portion.
```javascript
// .prettierrc.mjs
export default {
plugins: ['prettier-plugin-astro'],
// Skip formatting the JavaScript frontmatter
astroSkipFrontmatter: true,
// Format the template portion
printWidth: 100,
tabWidth: 2,
useTabs: false,
singleQuote: false,
trailingComma: 'all',
};
```
--------------------------------
### Default Options for Astro Files
Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/index.md
Provides the default formatting options, such as tab width, applied to all Astro files processed by the plugin.
```typescript
export const defaultOptions: {
tabWidth: number;
}
```
--------------------------------
### Asset Import Reference in Astro
Source: https://github.com/withastro/prettier-plugin-astro/blob/main/test/fixtures/markdown/embedded-in-markdown/output.md
Alternatively, assets can be organized alongside Astro components and imported within the component script. This method works but makes the asset's final URL less predictable compared to using the `public/` directory.
```astro
---
// ✅ Correct: references src/thumbnail.png
import thumbnailSrc from "./thumbnail.png";
---
```
--------------------------------
### Handle Null or Undefined Input
Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/get-visitor-keys.md
When provided with null or undefined input, getVisitorKeys returns an empty array, indicating no properties to visit.
```typescript
getVisitorKeys(null) // Returns: []
getVisitorKeys(undefined) // Returns: []
```
--------------------------------
### Astro Printer Interface
Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/api-reference/index.md
Defines the structure for the Astro printer, which converts Astro AST nodes into formatted output. Includes functions for printing, embedding, and visiting AST nodes.
```typescript
{
print: (path: AstPath, opts: ParserOptions, print: printFn) => Doc,
embed: (path: AstPath, opts: Options) => Embed,
getVisitorKeys: (node: any) => string[]
}
```
--------------------------------
### Importing Prettier Astro Plugin Types
Source: https://github.com/withastro/prettier-plugin-astro/blob/main/_autodocs/types.md
Provides the necessary import statements to use the various AST node types and configuration options from the 'prettier-plugin-astro' package in your TypeScript project.
```typescript
import type {
// Configuration
PluginOptions,
// AST Nodes
RootNode,
ElementNode,
ComponentNode,
CustomElementNode,
ExpressionNode,
TextNode,
DoctypeNode,
CommentNode,
FragmentNode,
FrontmatterNode,
AttributeNode,
Node,
ParentLikeNode,
TagLikeNode,
anyNode,
// Printer
ParserOptions,
AstPath,
} from 'prettier-plugin-astro';
// For Prettier types
import type { Doc, Parser, Printer, SupportLanguage, SupportOption } from 'prettier';
```
--------------------------------
### VS Code Settings for Prettier with Astro
Source: https://github.com/withastro/prettier-plugin-astro/blob/main/README.md
Configure VS Code to use the Prettier extension for formatting Astro files. These settings ensure that Prettier is recognized as the default formatter for *.astro files.
```json
{
"prettier.documentSelectors": ["**/*.astro"],
"[astro]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
```