Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webpacker: including javascript from a gem (js-routes)

I'm trying to use the JS routes gem with webpacker from Rails 5.1 but can't figure out how to include the js-routes.js.erb in webpack's app/javascript/packs/application.js.

import 'js-routes'

leads to

Uncaught Error: Cannot find module "js-routes"

Which likely means that webpack is unable to locate the javascript in the included gem. This is probably connected to this webpacker's github issue.

What is the best workaround for this issue right now?

Thanks!

like image 768
Juraj Masár Avatar asked Jul 11 '17 20:07

Juraj Masár


1 Answers

Using the technique described in the very advanced setup part of the JsRoutes documentation:

// app/javascript/routes.js.erb

<%= JsRoutes.generate %>
export default this.Routes

And then in your application pack:

// app/javascript/packs/application.js

import Routes from '../routes.js.erb'
// Note the .erb extension!

// If you want it to be available globally for some reason:
window.Routes = Routes
like image 126
Thomas Bailey Avatar answered Nov 08 '22 10:11

Thomas Bailey