Nuxt.js: Velocity.js doesn't work as ssr: false plugin, how to use it?

Created on 4 Nov 2017  路  26Comments  路  Source: nuxt/nuxt.js

I have a plugin

import Velocity from 'velocity-animate'

export {
  Velocity
}

Using it with ssr: false

Then import it in component as import Velocity from '~/plugins/velocity'

I got an error in console

[vue-router] Failed to resolve async component default: ReferenceError: window is not defined
[vue-router] uncaught error during route navigation:
ReferenceError: window is not defined

And in browser

Cannot read property 'options' of undefined

This question is available on Nuxt.js community (#c1800)

Most helpful comment

We solved it on vue discord

Plugin code then simply use it in components, pages etc.. this.$velocity

import Velocity from 'velocity-animate'

export default (ctx, inject) => {
  inject('velocity', Velocity)
}

All 26 comments

I made it work only with this ugly hack, which is inappropriate

enter: function (el, done) {
      if (process.browser) {
        const Velocity = require('velocity-animate')
        Velocity(
          el,
          'slideDown',
          {
            duration: 200,
            easing: 'easeInBack'
          },
          { complete: done }
        )
      }
    }

Please help how to use it?

We solved it on vue discord

Plugin code then simply use it in components, pages etc.. this.$velocity

import Velocity from 'velocity-animate'

export default (ctx, inject) => {
  inject('velocity', Velocity)
}

@Samuell1 thanks, very helpful!

for me this worked in nuxt.config.js after "yarn add velocityjs":

plugins: [{src: '~/plugins/velocity', ssr: true},
build: {vendor: ['velocity-animate', 'ks-vue-fullpage'],

and velocity.js:

import Vue from 'vue'
import Velocity from 'velocity-animate'
Vue.use(Velocity)

@gianniskarmas how is that possible, Velocity is not a Vue.js plugin?

You make it one ;)

I don't really understand how it works but it does. I am also new with nuxt and spent so many hours reading nuxt documentation as to make ks-vue-fullpage to work.

Inside plugins folder create the velocity.js file with the above contents and call it from main nuxt.config.js

This line is the key: build: {vendor: ['velocity-animate'].
after adding it it stopped giving me errors and started animating.
Also using asyncData and ssr true it seems the ssr also works.
Someone with greater knowledge please explain how this is possible.

Try it and let me know if it works for you too.

My dudes @gianniskarmas @hackuun @Samuell1(whoops) why are you doing this? :pizza:
Just require it directly in the components you use it.
This is how you should use any plugin that doesn't require instantiating a global object with state.

I think you may have meant @Samuell1 :)

@gianniskarmas it works because it doesn't do anything.
You just import it (in the plugin file).
Then you Vue.use() it. This does Velocity(Vue) basically, which does nothing since Vue is not a HTMLElement
Then the plugin ends, and we are back to the real world.

I thought this was solved 4 months ago, or no?

@Samuell1 oh, it is solved, it's just resurrected for some reason. :smile:

By the way, Velocity is freaking awesome!

@Samuell1 I wouldn't call including it into every page and putting a reference in context for a static function "solved".

@qm3ster hi. How do you propose to use it in component directly? We need to set it as ssr: false or require it only in browser. The only way I could find is the example above.

I mean, this is awful

enter: function (el, done) {
      if (process.browser) {
        const Velocity = require('velocity-animate')
        Velocity(
          el,
          'slideDown',
          {
            duration: 200,
            easing: 'easeInBack'
          },
          { complete: done }
        )
      }
    }

Then how to use it with Nuxt?

I'd love to see a working example of @qm3ster's solution, because that was the first thing I tried and it threw a 'window not defined' error.

@Samuell1's solution gives 'TypeError: this.$velocity is not a function'

Been using this for about 6 months

// my velocity plugin
import velocity from 'velocity-animate/velocity.min.js'

export default (ctx, inject) => {
  ctx.$velocity = velocity
  inject('velocity', velocity)
}
plugins: [
   ...,
   { src: '~plugins/velocity.js', ssr: false }
]

@JGJP do you created plugin and imported in nuxt.config?

@uptownhr
.velocity is not a function

have you tried $velocity?

@uptownhr yea , btn.css(...).$velocity is not a function

@andysay this.$velocity

@Samuell1 Uncaught TypeError: Cannot read property '$velocity' of undefined

    btn.css('position', 'fixed').this.$velocity({
      top: top - btnRadius,
      left: left - btnRadius,
      translateX: 0,
    }, 0);

  function animateLayer(layer, scaleVal, bool) {
    layer.this.$velocity({ scale: scaleVal }, 400, function(){
      $('body').toggleClass('overflow-hidden', bool);
      (bool) 
        ? layer.parents('.cd-section').addClass('modal-is-visible').end().off('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend')
        : layer.removeClass('is-visible').removeAttr( 'style' ).siblings('[data-type="modal-trigger"]').removeClass('to-circle');
    });
  }

@andysay you need to share your entire code for us to help. You not using this in the right context.

@uptownhr

i use this

`mounted() {

jQuery(document).ready(function($){
//trigger the animation - open modal window
$('[data-type="modal-trigger"]').on('click', function(){
var actionBtn = $(this),
scaleValue = retrieveScale(actionBtn.next('.cd-modal-bg'));

    actionBtn.addClass('to-circle');
    actionBtn.next('.cd-modal-bg').addClass('is-visible').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
        animateLayer(actionBtn.next('.cd-modal-bg'), scaleValue, true);
    });

    //if browser doesn't support transitions...
    if(actionBtn.parents('.no-csstransitions').length > 0 ) animateLayer(actionBtn.next('.cd-modal-bg'), scaleValue, true);
});

//trigger the animation - close modal window
$('.cd-section .cd-modal-close').on('click', function(){
    closeModal();
});
$(document).keyup(function(event){
    if(event.which=='27') closeModal();
});

$(window).on('resize', function(){
    //on window resize - update cover layer dimention and position
    if($('.cd-section.modal-is-visible').length > 0) window.requestAnimationFrame(updateLayer);
});

function retrieveScale(btn) {
    var btnRadius = btn.width()/2,
        left = btn.offset().left + btnRadius,
        top = btn.offset().top + btnRadius - $(window).scrollTop(),
        scale = scaleValue(top, left, btnRadius, $(window).height(), $(window).width());

    btn.css('position', 'fixed').this.$velocity({
        top: top - btnRadius,
        left: left - btnRadius,
        translateX: 0,
    }, 0);

    return scale;
}

function scaleValue( topValue, leftValue, radiusValue, windowW, windowH) {
    var maxDistHor = ( leftValue > windowW/2) ? leftValue : (windowW - leftValue),
        maxDistVert = ( topValue > windowH/2) ? topValue : (windowH - topValue);
    return Math.ceil(Math.sqrt( Math.pow(maxDistHor, 2) + Math.pow(maxDistVert, 2) )/radiusValue);
}

function animateLayer(layer, scaleVal, bool) {
    layer.this.$velocity({ scale: scaleVal }, 400, function(){
        $('body').toggleClass('overflow-hidden', bool);
        (bool) 
            ? layer.parents('.cd-section').addClass('modal-is-visible').end().off('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend')
            : layer.removeClass('is-visible').removeAttr( 'style' ).siblings('[data-type="modal-trigger"]').removeClass('to-circle');
    });
}

function updateLayer() {
    var layer = $('.cd-section.modal-is-visible').find('.cd-modal-bg'),
        layerRadius = layer.width()/2,
        layerTop = layer.siblings('.btn').offset().top + layerRadius - $(window).scrollTop(),
        layerLeft = layer.siblings('.btn').offset().left + layerRadius,
        scale = scaleValue(layerTop, layerLeft, layerRadius, $(window).height(), $(window).width());

    layer.this.$velocity({
        top: layerTop - layerRadius,
        left: layerLeft - layerRadius,
        scale: scale,
    }, 0);
}

function closeModal() {
    var section = $('.cd-section.modal-is-visible');
    section.removeClass('modal-is-visible').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
        animateLayer(section.find('.cd-modal-bg'), 1, false);
    });
    //if browser doesn't support transitions...
    if(section.parents('.no-csstransitions').length > 0 ) animateLayer(section.find('.cd-modal-bg'), 1, false);
}

});
}`

You using jQuery, for that you need to use it in other way

Import velocity as scriptsrc (https://raw.githubusercontent.com/julianshapiro/velocity/master/velocity.min.js) then use as you before asked element.velocity(...)

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bimohxh picture bimohxh  路  3Comments

VincentLoy picture VincentLoy  路  3Comments

bimohxh picture bimohxh  路  3Comments

o-alexandrov picture o-alexandrov  路  3Comments

maicong picture maicong  路  3Comments