12

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?

kissu
  • 40,416
  • 14
  • 65
  • 133
Moon
  • 33,439
  • 20
  • 81
  • 132
  • This was [the solution](https://stackoverflow.com/a/67535277/8816585) for nuxt2. Here is the related topic for Nuxt3: https://github.com/nuxt/framework/issues/5565 – kissu Jul 03 '22 at 18:09

1 Answers1

22

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!');" }],
    },
  },
});
Moon
  • 33,439
  • 20
  • 81
  • 132