External JS in Sage (bodyScrollLock not defined)

Good afternoon,

I’m having a bit of an issue with external JS import.
The documentation doesn’t make it very clear on what the best path is. I followed the instructions (as per slick) and made no headway.

Firstly I added the package with yarn:
yarn add body-scroll-lock --dev

Then I added this to the top of the common.js file:
import bodyScrollLock from 'body-scroll-lock/lib/bodyScrollLock.min';

And then under “finalize(){” again in common JS this fails everytime:
const disableBodyScroll = bodyScrollLock.disableBodyScroll;
const enableBodyScroll = bodyScrollLock.enableBodyScroll;

With the error:
common.js:31 Uncaught TypeError: Cannot read property 'disableBodyScroll' of undefined
at Object.finalize (common.js:31)
at Router.fire (Router.js:38)
at Router.loadEvents (Router.js:67)
at HTMLDocument.<anonymous> (main.js:30) etc etc etc

I have tried the import in my main.js file which refused to compile and have been going around in circles looking for a solution to no avail ever since.

I’m sure I’m doing something really basic wrong but don’t know where to start troubleshooting.
Any tips or hints gratefully received and I thank you kindly in advance…

Side Q: Are these subjects covered in depth in the 'Theme Development With Sage" Book? If not could anyone point me to a source of learning tools on the subject. Thankyou! :slight_smile:

Your steps differ to what is in the readme of the package.
Follow the instructions listed here and that should give you what you need https://github.com/willmcpo/body-scroll-lock

1 Like

Ah OK, so I removed the import statement at the top of common.js
and added this above the code in the finalize statement:

const bodyScrollLock = require('body-scroll-lock');
And it works!

Thanks @codepuncher.

So would the general rule of thumb be to ignore the Roots/Sage docs and go with the docs of whichever package is being imported?

Does the book I mentioned above cover this in detail?

Ta Muchly! :smiley:

The correct way to import a JS package depends on that package. In order to work with import a package must be exporting something, and because that’s a relatively “new” standard not all packages do.

In general, yes, should always follow the instructions in the documentation on a particular package w/r/t to how to use it. The JS examples in Sage are just that; examples. They don’t represent the “correct” way of doing things, only one way of doing things.

1 Like

This topic was automatically closed after 42 days. New replies are no longer allowed.