logo
Adding external script tag to a nuxt app
by John Oba - Afrodev21 April, 2023 ā€¢ 2 min read
Image Banner

In this article, we will learn some tips on how to add an external script tag to a Nuxt app.

Adding a script globally in a Nuxt 3 app.

In the root directory of your Nuxt app, open the file nuxt.config.ts and add or edit the app section of the config. Here is an example:

Example 1:

<script src="https://example.com/script1.js" defer></script>
<script src="https://example.com/script2.js" async></script>

šŸ‘‡

export default defineNuxtConfig({
  ...
  app: {
    head: {
      script: [
        { src: 'https://example.com/script1.js', defer: true },
        { src: 'https://example.com/script2.js', async: true }
      ]
      ...
    },
  }
  ...
});

Looking at a more complex example like this

Example 2:

<script>
  (function () {
    console.log("A custom script in a nuxt app");
  })();
</script>

šŸ‘‡

export default defineNuxtConfig({
  ...
  app: {
    head: {
      script: [
        {
          children: `(function () {
              console.log("A custom script in a nuxt app");
           })()`
        } as any
      ]
      ...
    },
  }
  ...
});

Adding script with custom attributes

Example 3:

<script
  src="https://utteranc.es/client.js"
  repo="[ENTER REPO HERE]"
  issue-term="title"
  theme="github-dark"
  crossorigin="anonymous"
  async
></script>

these attributes are not spec-compliant for a <script> tag, but you can ignore them by adding as any after the script object: šŸ‘‡

export default defineNuxtConfig({
  ...
  app: {
    head: {
      script: [
        {
            src: 'https://utteranc.es/client.js',
            crossorigin: 'anonymous',
            async: true,
            'issue-term': 'title',
            repo: 'ENTER_REPO_HERE',
            theme: 'github-dark'
        } as any
      ]
      ...
    },
  }
  ...
});

Adding a script locally

In your .vue pages you can use the useHead composable

useHead({
    script: [
        // your scripts here
    ]
})

This composable is auto imported by Nuxt.

By following these simple steps, you can easily add an external script tag to your Nuxt app.

Cheers šŸ„‚


More Stories from Afrodev

2023 AfroDev