'Nuxt js How to import local js files from assets?
I tried all the ways to import the JS file and when i tried to navigate the script from the view source code it gives error "/* script not found */" .
i need to know what is the correct way to import local js scripts .
below is the nuxt.config.js file .
head: {
title: 'admin',
htmlAttrs: {
lang: 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' },
{ name: 'format-detection', content: 'telephone=no' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
],
script: [
{
type: 'text/javascript',
src: './assets/js/dashboard.js'
},
{
type: 'text/javascript',
src: '~/assets/plugins/charts-c3/plugin.js'
},
{
type: 'text/javascript',
src: '@/assets/plugins/maps-google/plugin.js'
},
{
type: 'text/javascript',
src: '/assets/plugins/input-mask/plugin.js'
}
],
},
Solution 1:[1]
Maybe take a look at Nuxt plugin property
You can use the script property for externally available scripts (try to put it in your static directory and add it like it : ./my-scripts.js
Solution 2:[2]
You can use the plugins key to import it globally to your Nuxt app (be careful of performance issues tho)
nuxt.config.js
export default {
plugins: ['~/plugins/vue-tooltip.js']
}
More info available here: https://nuxtjs.org/docs/2.x/directory-structure/plugins#the-plugins-property
If you want to use some 3rd party scripts that should be available in the header (which is not the case from the code you shared so far), you could look into this answer
nuxt.config.js
export default {
head: {
script: [
{ hid: 'stripe', src: 'https://js.stripe.com/v3/', defer: true }
]
}
}
Solution 3:[3]
I am using Nuxt v3 RC and updating nuxt.config.js did not help when using NuxtLayout.
I had to add the head to the default.vue layout to get external libraries to work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | lovis91 |
| Solution 2 | kissu |
| Solution 3 | Eric Aya |
