Getting Started
Emit static assets from Astro components and endpoints
Prerequisites
Section titled “Prerequisites”You will need to have an Astro website. If you don’t have one yet, you can follow the “Install Astro” guide to create one.
Installation
Section titled “Installation”astro-emit-asset is an Astro integration. Install it by running the following command in your terminal:
npx astro add astro-emit-assetpnpm astro add astro-emit-assetyarn astro add astro-emit-asset-
In the code where you want to emit an asset, import the
emitAsset()function from theastro-emit-asset/emitmodule:import { emitAsset } from 'astro-emit-asset/emit'; -
Create an asset by calling
emitAsset()with three arguments:- Your asset’s file name. This will be combined with a generated hash to make it safe to cache the asset indefinitely.
- Any variables your asset creation logic depends on. These will be used to invalidate caching if they change.
- A function to generate your asset. It should return an object with the file contents as a
dataproperty and an optionalmetaobject for metadata about your asset.
In the following example, the file name is
my.svg, there are no dependencies so an empty array is passed, and the asset generator returns an SVG string and some information about the dimensions of the SVG:const asset = await emitAsset('example.svg', [], () => {return {data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">)<circle fill="red" cx="50" cy="50" r="40" stroke="black" /></svg>`,meta: { width: 100, height: 100 },};}); -
Use the returned asset.
emitAsset()returns an object with asrcproperty with the path of your asset and ametaproperty containing any metadata your generator returned.In the following example, the asset from above is used to create an image element in an Astro component:
<img src={asset.src} width={asset.meta.width} height={asset.meta.height}>The resulting HTML will look something like:
<img src="/_astro/example.ZL7hak.svg" width="100" height="100" /> -
Happy emitting!
Does this work in on-demand routes?
Section titled “Does this work in on-demand routes?”No. On-demand rendering lets you run Astro’s rendering code on a server in response to user requests, but emitAsset() only works at build time in prerendered routes currently. On a server there may be no filesystem to persist an asset to and use of emitAsset() will fail.
What if I found a bug?!
Section titled “What if I found a bug?!”Astro Emit Asset is an open source project.
Please report issues you run into in the astro-emit-asset GitHub repository.
Acknowledgements
Section titled “Acknowledgements”The initial prototype of this integration was heavily based on an earlier prototype by Nate Moore. Thanks — as always — Nate!