Search code examples
javascriptruby-on-railswebpackbundlerwebpacker

How to load packages installed by `bundle` in webpack?


In a Ruby on Rails application, how can we require or import a package which was not installed via npm or yarn, but via bundle?

I tried:

//= require package-name

But that doesn't seem to work with webpacker.

require("package-name") doesn't work either (because it is not found in node_modules).


Solution

  • For normal Rails environment, you can use normal directory path if you want to require some files.

    Suppose your assets folder looks like this

    ├── application.js
    └── something.js
    

    and you want to require something.js then you just need to write

    //= require ./something.js
    

    to your application.js

    For a package that you manually place somewhere, then you have to add the place of packages to Rails.application.config.assets.paths

    If you are using Rails v5, you can check the config/initializers/assets.rb to see the magic of loading node_modules happened