有没有办法将 JavaScript 嵌入到 Vitepress markdown 模板中?

Jim*_*Lim 5 html javascript markdown vitepress vite

有没有办法将外部源的脚本以及本地脚本嵌入到 Vitepress markdown 中以生成它?

这个例子

## my test button

<script src="https://www.jsdeliver.com/sdk/js?yadayada"></script>
<script>
  function initButton() {
     ...
  }
</script>
Run Code Online (Sandbox Code Playgroud)

提出一个问题

[vite] hmr update /test/index.md (x2) 19:00:17 [vite] 内部服务器错误:具有副作用的标签( 和 )在客户端组件模板中被忽略。插件:vite:vue

Jim*_*Lim 5

第一种可能的方法是通过配置文件(.vitepress/config.js),可以将脚本嵌入到生成的 vitepress index.html 中。文档没有很好地解释它,但是如果我们需要将脚本放入 header 中,那么这是有效的。

以下是 google 标签标头脚本的示例。

export default {
  title: 'mydocumentation',
  head: [
    [
      'script',
      {
        async: true,
        src: 'https://www.googletagmanager.com/gtag/js?id=G-xxxxxxxxx'
      }
    ],
    [
      'script',
      {},
      `
      window.dataLayer = window.dataLayer || [];
      ...

      gtag('config', 'G-xxxxxxxxxxx');
      `
    ]
  ]
}
Run Code Online (Sandbox Code Playgroud)