Magic Imports: Using Components Without Importing Them
In our previous post, we saw how Astro components can clean up our Markdown. But there was one catch: we still had to import them at the top of every file.
---
import ScribbleBox from '../../components/scribble/ScribbleBox.astro';
// ... more imports
---
This gets repetitive. Wouldn’t it be nice if these components were just available, like standard HTML tags?
The Solution: Global Injection
We’ve updated our blog layout to automatically pass our “Active Whiteboard” components to every MDX post. This means you can now use <ScribbleBox>, <Chart>, and others without writing a single import statement!
Example: No Imports Required!
I’m using the <ScribbleBox> component right here, and if you check the source of this file, you’ll see zero imports.
Look Ma, No Imports! This component was injected globally by the layout.
How It Works
In our [...slug].astro layout, we pass a components object to the <Content /> component:
// src/pages/blog/[...slug].astro
import ScribbleBox from '../../components/scribble/ScribbleBox.astro';
// ... other imports
const components = {
ScribbleBox,
// ... other components
};
// ...
<Content components={components} />
This simple change saves time and keeps your Markdown files focused purely on content.
Layout
Imports Once
MDX Files
Use Everywhere
Available Components
Currently, the following components are available globally:
<ScribbleBox><ScribbleHighlight><ScribbleCircle><DiagramArrow><Chart>
Happy writing!