Skip to content

Add napi-image support to Astro project

Posted on:December 17, 2022

Table of contents

Open Table of contents

The Why

According to this benchmark, @napi-rs/image is 2x faster than sharp and without involving node-gyp.

How

We know that astro is a vite-based project, so most of vite plugins can be painlessly added to your project. As it happens, rollup-plugin-napi-image is compatible with astro, we just need to add it to astro.config.mjs 1, like the following:

import { defineConfig } from 'astro/config'
// ...other plugins
import { napiImage } from 'rollup-plugin-napi-image'

// https://astro.build/config
export default defineConfig({
  integrations: [/** integrations **/],
  vite: {
    plugins: [
      napiImage({
        type: 'lossy',
        quality: 75
      })
    ]
  },
})

But you will soon find that the images brought in from the public folder in your markdown files are not compressed, this is because the files in the public folder are simply copied into the bundle during the build session and nothing else is done with them.

How to solve this problem

rollup-plugin-napi-image only compresses the images imported by source code, therefore we need the format that can import assets directly from path — mdx.

Add mdx support

npx astro add mdx
# or you use pnpm
pnpm astro add mdx

Import assets in your code

  1. rename your desired md file with mdx-suffixed.
  2. import it :
import myImage from '../path/to/image'
  1. consume it :
<img src={myImage} alt={'my-image'} />

Footnotes

  1. astro docs