rubygemswebpack-4ruby-2.7ruby-on-rails-6

How to use third party js in rails 6 using webpack?


using ruby 2.7.1p83 and Rails 6.0.3.2 in rails project.

imported huebee inside the rails appliction webpack.

 yarn add huebee

imported its css and js files for the in the application.js and application.css files respectively:

for application.js
import 'huebee/huebee';
for application.css
@import "~huebee/huebee";

Now, if

 <input class="color-input" data-huebee='{ "notation": "hex", "saturations": 2 }'/>

enter image description here

is working fine and showing the drow box for colour selector:

but when I initialise the Huebee object inside js it given error as:

var hueb = new Huebee('.color-sample', {
    notation: 'hex',
    saturations: 2,
    staticOpen: true,
    hues: 6,

});

enter image description here enter image description here

Uncaught ReferenceError: Huebee is not defined

please suggest the right approach to fix this issue thanks in advance.

my user.js file where Huebee is imported as:

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

import "jquery";
import "jquery-ui";
import "popper.js";
import "bootstrap";
import 'owl.carousel';
import 'jquery.easing';
import "@fortawesome/fontawesome-free/js/all";
import "@fortawesome/fontawesome-free/css/all.css";
import '../stylesheets/user.scss';
import Huebee from 'huebee/huebee';
require.context('../images', true, /\.(png|jpe?g|svg)$/);

user.scss file:

@import '~bootstrap';
@import '~owl.carousel2/dist/assets/owl.theme.default';
@import '~owl.carousel2/dist/assets/owl.carousel';
@import "~huebee/huebee";

Huebee script for initialisation:

(function () {
    const element= document.querySelector('.color-sample');
    var hueb = new Huebee(element, {
        notation: 'hex',
        saturations: 2,
        staticOpen: true,
        hues: 6,
    });
})();

This gives following error: enter image description here


Solution

  • You need to import Huebee class from the package.

    In application.js

    import Huebee from 'huebee/huebee';
    

    In your js code, pass element as reference instead of directly passing .color-sample. And make sure the following code runs after document load.

    const element= document.querySelector('.color-input');
    var hueb = new Huebee(element, {
        notation: 'hex',
        saturations: 2,
        staticOpen: true,
        hues: 6,
    });