DEV Community

Cover image for Astro Command unlocks the world
Stephen Solka
Stephen Solka

Posted on

Astro Command unlocks the world

Introduction

This weekend I built a new Astro component that lets callers use external commands on their machine to generate html content.

GitHub logo trashhalo / astro-command

run commands as astro components

In the repository there is a hello world demo that is shelling out to python.

--------
import { Command } from "astro-command";
--------
<Command caller={import.meta.url} command="./Component.py" message="from python!" />
Enter fullscreen mode Exit fullscreen mode
#!/usr/bin/env python 

import sys, json

data = json.load(sys.stdin)
print(f'<h1> Hello {data["message"]} </h1>')
Enter fullscreen mode Exit fullscreen mode

Props are passed in as a json blob to stdin. Html comes out stdout.

Taking it up a notch

Python has a very deep well of libraries that can be useful for astro page generation. One example is https://matplotlib.org/ a plotting library that can generate beautiful graphs outputting SVG.

As a quick example I rewrote the hello world py component to output a graph instead.

Screenshot 2021-09-19 144501

Its not just python

Now that you have shell access from Astro you can use any command! The first one I created a custom component for is Pandoc to get access to all the types of content Pandoc can understand. With 12 lines of astro code I unlocked 30+ file formats!

Astro Pandoc

Astro component for using pandoc to convert content. This allows you to embed any format pandoc supports.

Usage

---
import { Pandoc } from "astro-pandoc"
---
<Pandoc caller={import.meta.url} file="Component.tex" extraArgs={["--webtex"]} /
Enter fullscreen mode Exit fullscreen mode

Component.tex

\documentclass{article}
\usepackage{amsmath} % for the equation* environment
\begin{document}
This is a simple math expression \(\sqrt{x^2+1}\) inside text. 
And this is also the same: 
\begin{math}
\sqrt{x^2+1}
\end{math}
but by using another command.

This is a simple math expression without numbering
\[\sqrt{x^2+1}\] 
separated from text.

This is also the same:
\begin{displaymath}
\sqrt{x^2+1}
\end{displaymath}

\ldots and this:
Enter fullscreen mode Exit fullscreen mode

Whats next?

There are lots of commands out there. Which one should I connect to astro next?

Discussion (0)