Requiring a sprockets-preprocessed file with Browserify and browserify-rails

徘徊边缘 提交于 2019-12-04 06:53:53

I’ve spent endless hours on integrating browserify-rails in my project and making JS Routes work within this setup…

The solution I came to and described below is the result of me not being able to have Sprockets pre-process my routes file before Browserify would come in. I have spent quite some time in both the source code of browserify-rails and sprockets but couldn't find a way to turn things around and have each component act in the correct order for this to work.

So my solution was to use a Rails hook to generate the complete JS file « by hand » in the development environment, so that routes are always up to date with the latest Rails routes files. I then assume the routes JS file will be up to date when pushing to production.

Doing so in the environment loading makes sure the JS file is ready before Sprockets/browserify chime in: for them it’s just another plain JS file.

Here's the code to include in development.rb:

ActionDispatch::Reloader.to_prepare do
  Rails.application.reload_routes!

  if JsRoutes.assert_usable_configuration!
    JsRoutes.generate!(Rails.root.join('app/assets/javascripts/routes.js'))
  end
end

You'll want to always reload routes, otherwise the generated file will always represent the second to last state of the Rails routes file. I never figured out why...

In my application.js, I then just removed all //= directives but the jQuery ones (to keep a global jQuery available), and used the require method for all other modules so that browserify would pick the files I want to include.

So this is a bit hacky, but it does work.

I'd be interested to see whether someone with better knowledge of the Sprockets pipeline could come with a better solution?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!