Search code examples
javascriptruby-on-railswebpackturbolinkswebpacker

how to install bs-stepper with webpacker in rails 6?


I have installed it using yarn add bs-stepper

and I have load the library into my environment.js

const { environment } = require("@rails/webpacker");

const webpack = require("webpack");

environment.plugins.append(
  "Provide",
  new webpack.ProvidePlugin({
    $: "jquery",
    jQuery: "jquery",
    Popper: ["popper.js", "default"],
    Stepper: "bs-stepper",
  })
);

module.exports = environment;

and I already make an instance of it on my pack/application.js

import Rails from "@rails/ujs";
import Turbolinks from "turbolinks";
import * as ActiveStorage from "@rails/activestorage";
import "channels";
import "bootstrap";
import "../stylesheets/application";
require("admin-lte");
import "@fortawesome/fontawesome-free/js/all";

document.addEventListener("turbolinks:load", () => {
  $('[data-toggle="tooltip"]').tooltip();
  var stepper = new Stepper($(".bs-stepper")[0]);
});

Rails.start();
Turbolinks.start();
ActiveStorage.start();

require("trix");
require("@rails/actiontext");
import "controllers";

but the code is not working when I click this button

<button class="btn btn-primary" onclick="stepper.next()">Next</button>

I got this error

(index):223 Uncaught ReferenceError: stepper is not defined
    at HTMLButtonElement.onclick ((index):223)

I think its because my html is cannot find stepper that declared in application.js


Solution

  • the problem is the way I set the instance of Stepper

    I need to explicitly attach it to the window's variable like this

    document.addEventListener("turbolinks:load", () => {
      $('[data-toggle="tooltip"]').tooltip();
      window.stepper = new Stepper($(".bs-stepper")[0]);
    });