Astro M²DX - Vite plugin to export component mappings per-directory
DEPRECATED: Please consider using the plugin astro-m2dx, which bundles all features from the different
@astro-m2dx
plugins in one plugin (all features are opt-in).
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 to add support for automatic components
mapping insertion to markdown-files in the context of Astro site generation.
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 per directory.
When should I use this?
If you want to use the same component mapping for all MDX-files within a directory and its subdirectories and want to keep your markdown files and their frontmatter as clean as possible.
Install
This package is ESM only.
In Node.js (version 12.20+, 14.14+, or 16.0+), install with npm
:
npm install -D @astro-m2dx/vite-astro-mdx-mapping
Use
In your astro.config.mjs
import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
import mdxMapping from '@astro-m2dx/vite-astro-mdx-mapping';
// ^^^
// https://astro.build/config
export default defineConfig({
integrations: [mdx()],
markdown: {
remarkPlugins: [],
extendDefaultPlugins: true,
},
vite: {
plugins: [mdxMapping()],
// ^^^
},
});
This uses the default options, where the name of the mapping file is _mdx-mapping.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: [mdxMapping({name: "_components.ts"})],