问题
如何替换";段落";节点到";html";MDX的节点?
背景
将每个";twitter网站";指向扩展的Twitter的链接在MDX内容中嵌入HTML。
可复制代码沙盒:https://codesandbox.io/s/dazzling-curran-2bcwe?file=/src/index.mjs:2024-3439
问题
我有一个MDX内容,其中包含推特链接列表(例如。https://twitter.com/BrendanEich/status/1151317825908166656),并且替换段落节点导致以下错误
/node_modules/ebuild/lib/main.js:869:27:错误:[plugin:esbuild xdm]无法读取未定义的属性"line"at failureErrorWithLog(/ssandbox/node_modules/ebuild/lib/main.js:1449:15)位于/ssandbox/nod_module/ebuild/lib/main.js:11131:28在runOnEndCallbacks(/ssandbox/nod_module/ebuild/lib/main.js:921:63)在buildResponseToResult(/ssandbox/node_modules/ebuild/lib/main.js:1129:7)位于/ssandbox/node_modules/ebuild/lib/main.js:1236:14位于/ssandbox/nod_module/ebuild/lib/main.js:609:9在handleIncomingPacket(/ssandbox/node_modules/ebuild/lib/main.js:706:9)位于Socket.readFromStdout(/ssandbox/node_modules/ebuild/lib/main.js:576:7)在Socket.eemit(events.js:315:20)在addChunk(internal/streams/readable.js:309:12)
有问题的代码
const remarkTwitter = (options) => {
return transformer;
async function transformer(tree) {
// gather Twitter links
visit(tree, "paragraph", (node) => {
if (isTwitterLink(node)) {
const tweetLink = node.children[0].value;
tweetNodeList.push([node, tweetLink]);
}
});
// Build Tweet embed HTML
// and replace the current node
for (let i = 0; i < tweetNodeList.length; i++) {
const twitterNode = tweetNodeList[i];
const node = twitterNode[0];
const tweetLink = twitterNode[1];
try {
const embedData = await getEmbeddedTweet(tweetLink, options);
node.type = "html";
node.value = embedData.html;
return node;
} catch (err) {
console.error(err);
}
}
}
};
我使用的不是我的自定义插件,而是@remark-embedder/core-plugin-
以下是使用该插件的代码部分。
import remarkEmbedder from "@remark-embedder/core";
// other imports...
const getMDXOptions = (year: number, slug: string) => {
const cwd = `${getBlogRoot(year, slug)}`;
const imagesUrl = `/images/blog/${year}/${slug}`;
return {
cwd,
xdmOptions: (options: any) => {
options.format = "mdx";
options.allowDangerousRemoteMdx = true;
options.rehypePlugins = [twitterWidgetScriptPlugin];
options.remarkPlugins = [
remarkMdxImages,
[
remarkEmbedder,
{
transformers: [
githubGistTransformer,
codeSandboxTransformer,
[oembedTransformer, oembedConfig],
],
handleHTML,
},
],
];
return options;
},
esbuildOptions: (options: BuildOptions) => {
options.outdir = path.join(process.cwd(), "public", imagesUrl);
options.loader = {
...options.loader,
".png": "file",
".jpg": "file",
".gif": "file",
".svg": "file",
};
options.publicPath = imagesUrl;
options.write = true;
return options;
},
};
};