5

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!

3 Answers3

5

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
Thomas Bailey
  • 66
  • 1
  • 3
  • One notice, if you get error like: "Module build failed: SyntaxError: Unexpected token (1:0)". You probably don't have erb loader. To install it you should read short description on webpacker docs: https://github.com/rails/webpacker#erb – Michał Zalewski May 29 '18 at 18:34
0

If you want more js only dev process, you can

  1. pre-generated app/assets/javascripts/routes.js with built-in task rake js:routes
  2. add to

    # config/webpacker.yml 
    ...
    resolved_paths: ['app/assets/javascripts']
    ...
    
  3. reference them as import routes from './routes.js'

  4. regenerate it after any routing changes with rake js:routes
pocheptsov
  • 1,936
  • 20
  • 24
0

If you are using webpacker, you might want to check out js_from_routes, which doesn't require advanced setup, as it's designed for an import-based setup.

For each endpoint that you'd like to access from JS, it will generate a method that can help you build a URL or make a request.

resources :video_clips, export: true

By using it in combination with axios, these generated helpers can be convenient and easy to use:

import VideoClipsRequests from '@requests/VideoClipsRequests'

VideoClipsRequests.update({ data: video })
  .then(onVideoUpdate)

Have in mind that you can adjust the generated code by providing a custom template.

Benefits:

  • Easily specify which routes should generate a helper.
  • No need to manually specify the URL, preventing mistakes and saving development time.
  • Plays nicely with tree-shaking, unused helpers are not included in the compiled bundle.
Maximo Mussini
  • 1,030
  • 11
  • 19