2022-06-30 13:11:12 -05:00
|
|
|
import type { AstroIntegration } from 'astro';
|
2022-07-20 09:56:32 -05:00
|
|
|
import mdxPlugin from '@mdx-js/rollup';
|
|
|
|
import { parse as parseESM } from 'es-module-lexer';
|
|
|
|
import { getFileInfo } from './utils.js';
|
2022-06-30 13:09:09 -05:00
|
|
|
|
|
|
|
export default function mdx(): AstroIntegration {
|
|
|
|
return {
|
2022-06-30 13:11:12 -05:00
|
|
|
name: '@astrojs/mdx',
|
|
|
|
hooks: {
|
2022-07-20 09:56:32 -05:00
|
|
|
'astro:config:setup': ({ updateConfig, config, addPageExtension, command }: any) => {
|
2022-06-30 13:11:12 -05:00
|
|
|
addPageExtension('.mdx');
|
|
|
|
updateConfig({
|
|
|
|
vite: {
|
|
|
|
plugins: [
|
|
|
|
{
|
|
|
|
enforce: 'pre',
|
|
|
|
...mdxPlugin({
|
|
|
|
jsx: true,
|
|
|
|
jsxImportSource: 'astro',
|
|
|
|
// Note: disable `.md` support
|
|
|
|
format: 'mdx',
|
|
|
|
mdExtensions: [],
|
|
|
|
}),
|
|
|
|
},
|
2022-07-20 09:56:32 -05:00
|
|
|
{
|
2022-06-30 13:11:12 -05:00
|
|
|
name: '@astrojs/mdx',
|
|
|
|
transform(code: string, id: string) {
|
|
|
|
if (!id.endsWith('.mdx')) return;
|
2022-07-20 09:56:32 -05:00
|
|
|
const [, moduleExports] = parseESM(code);
|
|
|
|
|
|
|
|
if (!moduleExports.includes('url')) {
|
|
|
|
const { fileUrl } = getFileInfo(id, config);
|
|
|
|
code += `\nexport const url = ${JSON.stringify(fileUrl)};`;
|
|
|
|
}
|
|
|
|
if (command === 'dev') {
|
|
|
|
// TODO: decline HMR updates until we have a stable approach
|
|
|
|
code += `\nif (import.meta.hot) {
|
2022-06-30 13:09:09 -05:00
|
|
|
import.meta.hot.decline();
|
2022-07-20 09:56:32 -05:00
|
|
|
}`
|
|
|
|
}
|
|
|
|
return code;
|
2022-06-30 13:11:12 -05:00
|
|
|
},
|
|
|
|
},
|
|
|
|
],
|
|
|
|
},
|
|
|
|
});
|
|
|
|
},
|
|
|
|
},
|
|
|
|
};
|
2022-06-30 13:09:09 -05:00
|
|
|
}
|