Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function not working when importing other JS files

I'm using a simple script to check when something is in the viewport which then adds a class.

However the script stops working in Webpack when I try to import anything.

Below is basic example of importing which breaks my JS file. It doesn't matter what order I put the import and script etc.

window.jQuery = $;

import 'slick-carousel';

$(function ($, win) {
    $.fn.inViewport = function (cb) {
        return this.each(function (i, el) {
            function visPx() {
                var H = $(this).height(),
                    r = el.getBoundingClientRect(), t = r.top, b = r.bottom;
                return cb.call(el, Math.max(0, t > 0 ? H - t : (b < H ? b : H)));
            } visPx();
            $(win).on("resize scroll", visPx);
        });
    };
}(jQuery, window));


$(".preload").inViewport(function (px) {
  if (px) $(this).addClass("is-active");
});

If I remove import 'slick-carousel'; or any of my imports (its not specific to slick-carousel) the script stops working.

Here is an example the viewport script working.

like image 421
probablybest Avatar asked Sep 14 '26 14:09

probablybest


1 Answers

It seems to me that the import in itself might be wrong. Import in javascript is normally an url like:

import bar from './bar.js';

bar();

Using only import with module name is something you can do in node.

From documentation: "module-name: The module to import from. The evaluation of the specifier is host-specified. This is often a relative or absolute URL to the .js file containing the module. In Node, extension-less imports often refer to packages in node_modules. Certain bundlers may permit importing files without extensions; check your environment. Only single quoted and double quoted Strings are allowed."

Try adding the import with a relative or absolute url.

If this is not the issue. Please open the console and add the errormessage you get when running with the import.

like image 172
JohanSellberg Avatar answered Sep 17 '26 03:09

JohanSellberg