Search code examples
ruby-on-rails-4browserify-rails

Rails - access node_modules in application.js with browserify rails


The browserify-rails documentation says "By default only files in /app and /node_modules are browserified". However, when I install a package from npmjs and try to reference it in application.js, the app cannot find it. Is there a way to require node_modules in my Rails app using browserify-rails?

# command line
$ npm intl-tel-input --save

# application.js.coffee
#= require intlTelInput

# throws error
Error: Cannot find module 'intlTelInput' from '.../app/assets/javascripts'

Solution

  • When you use #= require ... then it still uses Rails asset pipeline and that will not be able to access the npm modules. What you should do instead is to use

    var intlTelInput = require("intlTelInput");
    

    which browserify will parse and find from the npm modules. If you have included an ES6 parser (like babelify) then you could even do it like this

    import intlTelInput from "intlTelInput"