Search code examples
javascriptruby-on-railswebpackparticles.js

Include particles.js into rails / webpack project


I have a project based on Rails 6.0.0.rc2 including webpack. I am trying to include simply the library particles.js

I am following the GitHub readme: - Install the library with yarn - Add a container with a specific id - Try to initialize the function using particlesJS.load

Obviously, it is not working: particleJS is not defined

particle_js__webpack_imported_module_0___default.a.load is not a function

After reading a lot of questions on this topic but nothing is really clear. here are some leads but I did not succeed:

I understood that particleJS is linked to the window object. And indeed, when I try in the console particleJS, it works.

So could you tell me simply how to use particleJS with webpack? Or how to use a window function into webpack?

Thank you in advance for your efforts!


Solution

  • Welcome to the Rails+webpacker mayhem. In theory you would do something like:

    let particlejs = require("particlejs"); 
    

    That goes in your pack file. Then you have particlejs available in your window object.

    You can also do:

    // config/webpack/custom.js
    module.exports = {
      resolve: {
        alias: {
          jquery: 'jquery/src/jquery',
          particle_js: 'particlejs'
        }
      }
    }
    

    Also try this:

    import 'particles.js/particles';
    const particlesJS = window.particlesJS;
    particlesJS.load('particles-js', 'particles.json', null);