Skip to content

Getting Started

If you are interested to learn more about JS From Routes before trying it, check out the Introduction.

Installation ๐Ÿ’ฟ

For a one-line installation, you can run this:

rails app:template LOCATION='https://railsbytes.com/script/X6ksgn'

Or, add this line to your application's Gemfile in the development group and execute bundle:

group :development, :test do
  gem 'js_from_routes'
end

And then, add a client library to your package.json:

npm install @js-from-routes/client # yarn add @js-from-routes/client

Usage ๐Ÿš€

Once the library is installed, all you need to do is:

Export the routes

Use export: true to specify which routes should be taken into account when generating JS.


ย 









Rails.application.routes.draw do
  resources :video_clips, only: [:show], export: true do
    get :download, on: :member
  end

  # Or:
  defaults export: true do
    # All routes defined inside this block will be exported.
  end
end

It will cascade to any nested action or resource, but you can opt out with export: false.

Refresh the page

Rails' reloader will detect the changes, and path helpers will be generated for the exported actions.

// app/frontend/api/VideoClipsApi.ts
import { definePathHelper } from '@js-from-routes/client'

export default {
  download: definePathHelper('get', '/video_clips/:id/download'),

  show: definePathHelper('get', '/video_clips/:id'),
}

A file will be generated per controller, with a path helper per exported action, although this is fully customizable.

You can run bin/rake js_from_routes:generate to trigger generation manually.

Use the generated helpers

Calling a helper will make a request and return a promise with the unwrapped JSON result.

import { videoClips } from '~/api'

const video = await videoClips.show({ id: 'oHg5SJYRHA0' })

Use path when you only need the URL. It will interpolate parameters, such as :id.

const downloadPath = videoClips.download.path(video)

You can also use an object that combines all helpers.

import api from '~/api'

const video = await api.videoClips.show({ id: 'oHg5SJYRHA0' })

const comments = await api.comments.index()

Depending on your use case, you may prefer to use this object instead of explicit imports.

Onwards ๐Ÿ›ฃ

You should now be able to get started with JS From Routes.

Have in mind that code generation is fully customizable; this is just the default way to use it.

For more information about using the helpers, check out this section.

If you would like to see a working example, check this repo.

Contact โœ‰๏ธ

Please visit GitHub Issues to report bugs you find, and GitHub Discussions to make feature requests, or to get help.

Don't hesitate to โญ๏ธ star the project if you find it useful!

Using it in production? Always love to hear about it! ๐Ÿ˜ƒ

Getting Started has loaded