'How can I reference js file from node_modules folder in page head in nuxt.js
I have added package onesignal-emoji-picker to my nuxt.js vue project and I want to reference css and js files in my pages without copying them to static folder. css is included with ease in nuxt.config.js:
css: ['~/node_modules/onesignal-emoji-picker/lib/css/emoji.css']
but I could not manage to reference js files, head.script section seems to work only for external resources:
script: [
{
src: 'https://code.jquery.com/jquery-3.3.1.slim.min.js',
type: 'text/javascript'
},
{
src: '~/node_modules/onesignal-emoji-picker/lib/js/config.js',
type: 'text/javascript'
},
{
src: '~/node_modules/onesignal-emoji-picker/lib/js/util.js',
type: 'text/javascript'
},
{
src: '~/node_modules/onesignal-emoji-picker/lib/js/jquery.emojiarea.js',
type: 'text/javascript'
},
{
src: '~/node_modules/onesignal-emoji-picker/lib/js/emoji-picker.js',
type: 'text/javascript'
}
]
It seems to me that I should somehow tell webpack to include this files on build and reference them appropriately? How could I do it? Thanks!
Solution 1:[1]
In nuxt.config.js, simply use the plugins key for including any internal scripts:
plugins: [
{ src: "~/node_modules/onesignal-emoji-picker/lib/js/config.js", mode: "client" },
{ src: "~/node_modules/onesignal-emoji-picker/lib/js/util.js", mode: "client" },
{ src: "~/node_modules/onesignal-emoji-picker/lib/js/jquery.emojiarea.js", mode: "client" },
{ src: "~/node_modules/onesignal-emoji-picker/lib/js/emoji-picker.js", mode: "client" }
]
Note the mode: "client" option which means the files will only be run on the client, preventing issues on the server if the library is not compatible with server-side-rendering. You may want to remove the flag in other cases.
Solution 2:[2]
Edit the file ./server/index.js and add the express static route just before this line app.use(nuxt.render).
The final start() function should be like this
async function start () {
...
app.use("/node_modules", express.static(path.join(__dirname, '/../node_modules')))
// Give nuxt middleware to express
app.use(nuxt.render)
....
}
After this change you can add node_modules libraries inside the vue page header.
export default {
head:{
script: [
{ src: "/node_modules/three/build/three.min.js", type: 'text/javascript', charset: 'utf-8'}
]
},
}
Solution 3:[3]
try to use nodes path library. I think it's one of the nuxt dependency so it should be already installed, if not just install it.
https://www.npmjs.com/package/path
Then import at the top of your nuxt.config.js
const path = require('path')
....
css: [path.resolve(__dirname, 'node_modules/onesignal-emoji-picker/lib/css/emoji.css')]
same thing with scripts
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 | kissu |
| Solution 2 | Sadegh Teimori |
| Solution 3 | BigKamil5 |


