@mdxvac/vite-astro-mdxcomponents
Vite plugin to define common component mappings for all Astro markdown files in a directory.
Content
What is this?
This package is a Vite
plugin in the context of Astro site generation.
When should I use this?
In Astro you can define a mapping from HTML elements to JSX components by exporting const components = { ... }
in any MDX file. With this plugin you can define this export per directory.
Install
This package is ESM only.
In Node.js (version 12.20+, 14.14+, or 16.0+), install with npm
:
npm install -D @mdxvac/vite-astro-mdxcomponents
Use
In your astro.config.mjs
import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
import mdxComponents from '@mdxvac/vite-astro-mdxcomponents';
// ^^^
// https://astro.build/config
export default defineConfig({
integrations: [mdx()],
markdown: {
remarkPlugins: [],
extendDefaultPlugins: true,
},
vite: {
plugins: [mdxComponents()],
// ^^^
},
});
This uses the default options, where the name of the mapping file is _components.ts
.
Now create a TypeScript/JavaScript file, that exports a components
object mapping HTML elements to arbitrary Astro, React, ... components.
import { Title } from '@components/Title';
export const components = {
h1: Title,
};
Options
If you want to use a different name for the mapping file, you can specify it in the plugin's name
option like so:
plugins: [mdxComponents({name: "_mapping.ts"})],