kampfkuchen
kampfkuchen

Reputation: 484

External Javascript files in nuxtjs

I am basing a website on an old tutorial, which uses 3 external js files. I am not able to recreate this using nuxtjs.

First, I tried to include the js files before the tag.

nuxt.config.js

head: {
    script: [
      { src: 'js/imagesloaded.pkgd.min.js', type: 'text/javascript', body: true, defer: true },
      { src: 'js/TweenMax.min.js', type: 'text/javascript', body: true, defer: true },
      { src: 'js/demo.js', type: 'text/javascript', body: true, defer: true }
    ]
  },

This works on initial page load. However, as soon as I change the page, the js files are ignored.


After some research, I tried to include the files as a plugin, to avoid ssr.

nuxt.config.js

plugins: [
    { src: "plugins/imagesloaded.pkgd.min.js", mode: 'client' },
    { src: "plugins/TweenMax.min.js", mode: 'client' },
    { src: "plugins/demo.js", mode: 'client' }
  ],

This gave me multiple error messages (amongst other things: 'Cannot read property addEventListener of null).

This is a very small project with a lot of time pressure, so any kind of help would be highly appreciated!


Update:

Original GitHub repository.

Upvotes: 7

Views: 3728

Answers (2)

Vuzi
Vuzi

Reputation: 185

To integrate bootstrap within antd-ui for my nuxt js project, this is what worked for me:

in nuxt.config.js, add the following

  1. add boostrap css files in css folder within assets folder:

    css: [ 'ant-design-vue/dist/antd.css', '~/assets/css/bootstrap.min.css', '~/assets/css/bootstrap-grid.min.css', '~/assets/css/bootstrap-utilities.min.css' ],

  2. add boostrap js files in js folder within static folder:

    plugins: [ '@/plugins/antd-ui', {src: '~/static/js/bootstrap.bundle.min.js', mode:'client'}, ],

This worked for me

Upvotes: -1

Jakub A Suplicki
Jakub A Suplicki

Reputation: 4801

Solution - steps to follow:


Add base.css to static > css folder, and also add all of the js files to static > js folder and then reference everything in nuxt.config.js:

    link: [
      { rel: 'stylesheet', type: 'text/css', href: 'css/base.css' }
    ],
    script: [
      { src: 'js/imagesloaded.pkgd.min.js', type: 'text/javascript', body: true, defer: true },
      { src: 'js/TweenMax.min.js', type: 'text/javascript', body: true, defer: true },
      { src: 'js/demo.js', type: 'text/javascript', body: true, defer: true }
   ]

Add all of the images to static > img folder and edit the base.css in order to reference images in base.css - write (wherever the images are referenced (2 places)): url('../img/1.jpg')

In the Vue template, copy-paste the HTML as-is.

When it comes to referencing images in the Vue template you would simply do:

<div class="background" style="background-image: url(img/1.jpg)"></div>

That is it. It should work just fine.


I created a GitHub repository so you can have a look and see how I have done it.


You can also view it live on CodeSandbox.

Upvotes: 6

Related Questions