How to Import Components in Astro: Simple Guide
In Astro, you import components using the
import statement at the top of your file, like import MyComponent from './MyComponent.astro'. Then you use the component as a tag in your template, for example, <MyComponent />.Syntax
To import a component in Astro, use the import statement followed by the component name and the path to the component file. Then use the component as a custom tag in your template.
- import: JavaScript keyword to bring in modules or components.
- ComponentName: The name you want to use for the component in your file.
- ./ComponentFile.astro: Relative path to the component file.
- <ComponentName />: How you use the imported component in your template.
astro
--- import ComponentName from './ComponentFile.astro'; --- <ComponentName />
Example
This example shows how to import a simple component called Greeting.astro and use it inside a page.
astro
--- import Greeting from './Greeting.astro'; --- <html lang="en"> <head> <title>Astro Import Example</title> </head> <body> <h1>Welcome to Astro!</h1> <Greeting /> </body> </html> <!-- Greeting.astro --> <h2>Hello from the Greeting component!</h2>
Output
<html lang="en">
<head>
<title>Astro Import Example</title>
</head>
<body>
<h1>Welcome to Astro!</h1>
<h2>Hello from the Greeting component!</h2>
</body>
</html>
Common Pitfalls
Common mistakes when importing components in Astro include:
- Forgetting the
.astroextension in the import path. - Using incorrect relative paths that do not point to the component file.
- Trying to use components without importing them first.
- Using uppercase component names in the import but lowercase tags in the template (component tags are case-sensitive).
astro
/* Wrong: Missing .astro extension */ import Greeting from './Greeting'; /* Right: Include .astro extension */ import Greeting from './Greeting.astro';
Quick Reference
Remember these tips when importing components in Astro:
- Always include the
.astrofile extension in the import path. - Use relative paths starting with
./or../. - Use PascalCase for component names and tags.
- Import components at the top of your Astro file before the template.
Key Takeaways
Use the
import statement with the correct relative path and .astro extension to bring in components.Use the imported component as a custom tag in your Astro template to render it.
Component names and tags are case-sensitive; use consistent PascalCase.
Always import components before using them in your template to avoid errors.
Check your file paths carefully to prevent import errors.