astro/packages/integrations/markdoc/src/index.ts

42 lines
1.2 KiB
TypeScript
Raw Normal View History

2023-02-06 16:13:57 +00:00
import type { AstroIntegration } from 'astro';
2023-02-06 16:21:17 +00:00
import type { InlineConfig } from 'vite';
2023-02-06 21:11:01 +00:00
import _Markdoc from '@markdoc/markdoc';
2023-02-06 16:13:57 +00:00
export default function markdoc(partialOptions: {} = {}): AstroIntegration {
return {
name: '@astrojs/markdoc',
hooks: {
'astro:config:setup': async ({ updateConfig, config, addPageExtension, command }: any) => {
addPageExtension('.mdoc');
console.log('Markdoc working!');
2023-02-06 23:09:23 +00:00
const markdocConfigUrl = new URL('./markdoc.config.ts', config.srcDir);
2023-02-06 16:21:17 +00:00
const viteConfig: InlineConfig = {
plugins: [
{
name: '@astrojs/markdoc',
async transform(code, id) {
if (!id.endsWith('.mdoc')) return;
2023-02-06 23:09:23 +00:00
return `import { Markdoc } from '@astrojs/markdoc';\nexport const body = ${JSON.stringify(
code
)};\nexport function getParsed() { return Markdoc.parse(body); }\nexport async function getTransformed(inlineConfig) {
let config = inlineConfig;
if (!config) {
try {
const importedConfig = await import(${JSON.stringify(markdocConfigUrl.pathname)});
config = importedConfig.default.transform;
} catch {}
}
return Markdoc.transform(getParsed(), config) }`;
2023-02-06 16:21:17 +00:00
},
},
],
};
updateConfig({ vite: viteConfig });
2023-02-06 16:13:57 +00:00
},
},
};
}
2023-02-06 21:11:01 +00:00
export const Markdoc = _Markdoc;