vue.jsnuxt.jsvuejs3nuxt3.js

How to add a script block to head in Nuxt 3?


I simply want to add a script block in the head tag.

Example

<script>
    alert('hello, world!');
</script>

I spent hours to figure out a solution for something as simple as this. There are tons of answers about adding inline scripts, but none for the script block for Nuxt 3

How can we do this in Nuxt 3?


Solution

  • Okay, I found the answer. There are 3 possible solutions.

    Solution 1

    <template>
      <Script children="console.log('Hello, world!');" />
    </template>
    

    Solution 2

    <script setup>
    useHead({
      script: [{ children: "console.log('Hello, world!');" }],
    });
    </script>
    

    Solution 3

    import { defineNuxtConfig } from 'nuxt';
    
    export default defineNuxtConfig({
      app: {
        head: {
          script: [{ children: "console.log('Hello, world!');" }],
        },
      },
    });