How to add external js file in Nuxt?
Asked Answered
T

4

6

I have js file called script.js in assets/js. Tried to include in nuxt.config.js like below:

head: {
    title: pkg.name,
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: pkg.description }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ],
      script: [
          { src: '/assets/js/script.js', ssr: false }
      ]
  }

But getting 'GET http://127.0.0.1:3000/assets/js/script.js 404 (OK)'.

Turtleback answered 25/9, 2018 at 10:7 Comment(0)
M
12

Simply keep your script.js file into static folder, because static folder treat as root folder.

and add the path into nuxt.config.js configuration file like below

script: [
          { src: '/script.js'}
      ]
Milburt answered 25/9, 2018 at 13:40 Comment(1)
This does not work if you use the router to redirect to a page.Reuter
S
4

here is the best way that worked for me

put your script.js file in plugins folder and then go and include it in nuxt.config.js

  // Plugins to run before rendering page (https://go.nuxtjs.dev/config-plugins)
  plugins: [
    '@/plugins/script.js'
  ],

remember that @ in nuxt.js or vue.js means root folder

Stomy answered 31/10, 2020 at 9:45 Comment(2)
how to use it in pages or components?Wieldy
@JenuelGanawed This gets automatically added to nuxt context object so where ever you access nuxt context object your plugin will be included you can check here nuxtjs.org/docs/directory-structure/pluginsStomy
J
1

In this method, your js files must be in the path static folder and add this code to you *.vue files you want to use

     export default {
head() {
return {
  link: [
    {
      rel: "stylesheet",
      href:
        "/assets/css/bootstrap.css"
    },
  ],
  script: [
    {
      src: "assets/js/bootstrap.js",
      body: true
    },
  ],
    }
  }
Jeaz answered 22/2, 2021 at 21:18 Comment(0)
B
0

If you have a utility js file, you can add it to utils/ and it will be available globally. Nuxt offical doc

Ballet answered 5/8 at 7:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.