Is there any way to embed JavaScript into Vitepress markdown template?

1.2k Views Asked by At

Is there a way to embed a script from external source as well as local script into Vitepress markdown for it to be generated?

This example

## my test button

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

throws up an issue

[vite] hmr update /test/index.md (x2) 19:00:17 [vite] Internal server error: Tags with side effect ( and ) are ignored in client component templates. Plugin: vite:vue

1

There are 1 best solutions below

1
On

a first possible way is through the config file (.vitepress/config.js) which is possible embed the scripts into the generated vitepress index.html. the documentation doesnt explain it well but this works if we need to place scripts into header.

the following is an example of google tag header script.

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');
      `
    ]
  ]
}