kswedberg / jquery-smooth-scroll

Automatically make same-page links scroll smoothly
MIT License
1.97k stars 427 forks source link

Using smoothScroll via NPM #109

Open imfaisalkh opened 6 years ago

imfaisalkh commented 6 years ago

I've installed this script using npm on my installation like this: npm install jquery-smooth-scroll. Now, in my javascript file i'm using this script like this:

import smoothScroll from 'jquery-smooth-scroll'

$('#page-controls .page-control.go-to-top').smoothScroll({
  offset: -150,
  speed: 600
});

The issue is, when I run the compiled (using babelify) js code this code throws the following error in the browser: smoothScroll is not a function

When I see my compiled .js file I can see that jquery.smooth-scroll.js is imported in it but still I get this error. Can you please tell what could be the issue here?

kswedberg commented 6 years ago

Hi @imfaisalkh , sorry for the late response. You should be able to just import it without the smoothScroll name:

import 'jquery-smooth-scroll'

That's how I do it, and it seems to work just fine.

imfaisalkh commented 6 years ago

Thanks for your reply @kswedberg I've tried simply importing it without any variable as you've mentioned but I'm still getting TypeError: e(...).smoothScroll is not a function error.

kswedberg commented 6 years ago

I'd have to see what else you're doing in your project to properly troubleshoot. My hunch is that there could be a problem with how you're bundling the JavaScript. If you're using something like webpack, you can expose $ and/or jQuery via the expose-loader. Or, probably a better approach is to import the plugin alongside jQuery:

import $ from 'jquery';
import 'jquery-smooth-scroll';
imfaisalkh commented 6 years ago

I'm building a WordPress theme, this CMS has jQuery script already included so I'm not importing it in my custom JS file. However, jQuery is available at run-time in the browser.

I've imported many other plugins this way (e.g. superfish, tendina ...) and they are working fine. Is there any way I can use smoothScroll without importing jQuery at build-time but by utilizing jQuery run-time version?

Note: I'm using gulp together with babelify to compile the JS file.

kswedberg commented 6 years ago

Thanks for the extra information. The "main" property in the package.json points to a built version of the plugin that uses the UMD pattern (since that was all the rage a couple years ago). I wonder if that's part of the problem here. Could you try to import the file from the src directory instead?

import 'jquery-smooth-scroll/src/jquery.smooth-scroll.js';