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)'.

4 Answers 4

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'}
      ]
Sign up to request clarification or add additional context in comments.

1 Comment

This does not work if you use the router to redirect to a page.
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

2 Comments

how to use it in pages or components?
@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/plugins
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
    },
  ],
    }
  }

Comments

0

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

Comments