如何在静态站点MDX文件中嵌入可执行Python代码并实现缓存?
解决MDX中可执行代码块的静态生成方案
针对你要在静态站点中处理MDX可执行代码块并缓存结果的需求,以下是分框架的落地方案:
一、Next.js + MDX 实现
Next.js原生支持MDX,通过自定义remark插件即可完成代码执行与结果注入:
编写自定义remark插件
插件负责识别python-exec代码块、执行代码、缓存结果,并修改MDX内容:// remark-exec-code.js import { execSync } from 'child_process'; import { createHash } from 'crypto'; import fs from 'fs'; import path from 'path'; import { visit } from 'unist-util-visit'; // 创建缓存目录 const cacheDir = './.code-exec-cache'; fs.mkdirSync(cacheDir, { recursive: true }); export default function remarkExecCode() { return (tree) => { visit(tree, 'code', (node) => { if (node.lang !== 'python-exec') return; // 生成代码哈希作为缓存键,确保代码不变就复用结果 const hash = createHash('sha256').update(node.value).digest('hex'); const cachePath = path.join(cacheDir, `${hash}.txt`); let output = ''; if (fs.existsSync(cachePath)) { // 读取缓存结果 output = fs.readFileSync(cachePath, 'utf8'); } else { // 执行Python代码,捕获错误 try { output = execSync(`python -c "${node.value.replace(/"/g, '\\"')}"`, { encoding: 'utf8' }); fs.writeFileSync(cachePath, output); } catch (err) { output = `执行错误:${err.message}`; } } // 将原代码块语言改为python,然后插入输出内容 node.lang = 'python'; const parent = tree.children; const index = parent.indexOf(node); // 插入Output标题和结果代码块 parent.splice(index + 1, 0, { type: 'paragraph', children: [{ type: 'text', value: 'Output:' }] }, { type: 'code', lang: null, value: output.trim() } ); }); }; }然后在
next.config.js中配置MDX插件:import createMDX from '@next/mdx'; import remarkExecCode from './remark-exec-code'; const withMDX = createMDX({ options: { remarkPlugins: [remarkExecCode], rehypePlugins: [], }, }); export default withMDX({ pageExtensions: ['js', 'jsx', 'md', 'mdx'], });缓存逻辑说明
- 用代码内容的SHA256哈希作为缓存文件名,只有代码变更时才会重新执行
- 缓存目录
.code-exec-cache可加入.gitignore,CI构建时可保留该目录复用缓存
二、SvelteKit/KitDocs 实现
SvelteKit用mdsvex处理MDX,逻辑和Next.js一致:
- 配置mdsvex插件
将上述remark-exec-code.js插件加入svelte.config.js的mdsvex配置:import { mdsvex } from 'mdsvex'; import remarkExecCode from './remark-exec-code'; export default { extensions: ['.svelte', '.md', '.mdx'], preprocess: mdsvex({ remarkPlugins: [remarkExecCode], }), };
三、通用第三方工具:mdx-exec
有现成工具mdx-exec支持多语言代码执行与缓存:
- 无需手动编写插件,直接加入MDX配置即可启用
- 支持Python、JavaScript等多种语言,自动处理代码执行与结果注入
- 内置哈希缓存机制,构建时自动跳过已缓存的代码块
四、核心注意事项
- 安全风险:仅处理可信的MDX文件,绝对不要执行用户提交的未知代码,防止代码注入
- 环境依赖:构建服务器需安装对应语言的运行时(比如Python)
- 缓存管理:可定期清理缓存目录,或在代码变更时自动失效对应缓存
内容的提问来源于stack exchange,提问作者tobiasBora
相关产品推荐
相关产品推荐

