A remark plugin to remove MDX import and export statements from markdown content.
When working with MDX files, you might want to:
- Extract just the markdown content for previews
- Process MDX without the React-specific code
- Create a pure markdown version of MDX content
- Generate documentation from MDX files while ignoring the component imports
This plugin makes it easy to strip away the MDX-specific import/export statements while preserving the regular markdown content.
# npm
npm install remark-strip-mdx-imports-exports
# yarn
yarn add remark-strip-mdx-imports-exports
# pnpm
pnpm add remark-strip-mdx-imports-exports
import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkMdx from 'remark-mdx';
import remarkStringify from 'remark-stringify';
import remarkStripMdxImportsExports from 'remark-strip-mdx-imports-exports';
async function processMdx(content) {
const result = await unified()
.use(remarkParse)
.use(remarkMdx)
.use(remarkStripMdxImportsExports)
.use(remarkStringify)
.process(content);
return String(result);
}
// Example MDX content
const mdxContent = `
import { Component } from 'react';
import { Chart } from './components/Chart';
# Hello World
This is some markdown content.
export const metadata = {
title: 'My Page'
};
## Another section
More content here.
`;
processMdx(mdxContent).then(result => {
console.log(result);
// Output will be:
// # Hello World
//
// This is some markdown content.
//
// ## Another section
//
// More content here.
});
// next.config.js
import remarkStripMdxImportsExports from 'remark-strip-mdx-imports-exports';
export default {
// ...
webpack: (config, options) => {
config.module.rules.push({
test: /\.mdx?$/,
use: [
options.defaultLoaders.babel,
{
loader: '@mdx-js/loader',
options: {
remarkPlugins: [remarkStripMdxImportsExports],
},
},
],
});
return config;
},
};
This plugin removes:
- ESM import statements:
import { Component } from 'react'
- ESM export statements:
export const metadata = { ... }
- MDX JSX flow elements with the name "import" or "export"
All other content, including regular markdown and JSX components used within the content, is preserved.
MIT