Roots Discourse

Unable to import javascript from npm package in Sage 9

I’ve installed an npm package called waypoints in my project folder. I am trying to import a javascript file called jquery.waypoints.min.js into the theme that is in the corresponding package folder in node_modules. I cannot get it to work even after adding it to config.json. I get a 404 error that says it doesn’t exist in the dist folder. How do you import custom javascript in Sage 9?

Using Sage 9 you should be able to import waypoints with:

import 'waypoints/lib/jquery.waypoints.min.js';

I’m having this same issue. Adding an import statement to main.js does not result in the file getting included when running ‘npm run build’. Oddly, it hot loads with the watch task. Not sure what it could be since I’m a bit new to webpack.

I have the same issue, anyone have found solution?

Same issue being you’re unable to use Waypoints or a different library? At the end of the day this is not a Sage specific issue.

I use waypoints, or at least I tried :slight_smile:
Anyway, it is imported, but calling waypoints function results in ‘function is not defined’, even
i checked and can see in main.js function exists.
Same happend with svg4everybody.

Not sure how can I debug this, just switched from gulp/bower to webpack. This is my third theme with new setup so still finding my way around.

There are definitely libraries where, seemingly at random (because I haven’t actually investigated when and why), you need to use import, or import function from library OR import function as function2 from library.

It’s not always clear which one will work with any given library and, like I said, I haven’t looked into what gives it away.

I’ve also had libraries like Headroom that just didn’t want to import no matter what.

So there are definitely challenges.

I ran in to this problem when I added Waypoints using 'npm install waypoints' I got it working by using 'yarn add waypoints' instead, you can then import into main.js using
import 'waypoints/lib/jquery.waypoints.js';

You are right, thanks for the tip.
I ended up with vanilla js instead of waypoints so didn’t test with that but looks like this is the solution.

It’s working now when I use:
import {svg4everybody} from 'svg4everybody/dist/svg4everybody.min';

I’ll chime in here too: perhaps it helps someone.

I found that when I had issues with certain imports, I was able to solve it by importing specific files (check node_modules which ones you want) such as with this scenario:

  1. Adding external library: in your theme root yarn add magnific-popup

  2. In your relevant stylesheet scss below @import "./autoload/**/*";:
    @import "~magnific-popup/dist/magnific-popup.css";

  3. In your relevant script file on top:
    import 'magnific-popup/dist/jquery.magnific-popup.js';