No commit activity in last 3 years
No release in over 3 years
COnvert Ruby on Rails routes to webpack js-route-loader format and export to a json file.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.16
~> 10.0
~> 3.0

Runtime

>= 5.1
 Project Readme

Gem Version test coverage

JsonRoutesWebpack

Exports Rails named routes to JSON that can be loaded in Javascript via webpack loaders like js-routes-loader

Installation

Add this line to your application's Gemfile:

gem 'json_routes_webpack'

And then execute:

$ bundle

Or install it yourself as:

$ gem install json_routes_webpack

Usage

Add a Rails initializer

Add an initializer that configures the routes you want to export and the file to write them too

config/initializers/json_routes_webpack.rb

JsonRoutesWebpack.configure do |config|
  config.add_routes 'app/javascript/generated/routes.json'
end

In addition to the file name to write the routes add_routes supports two options arguments

  • include - an array of regular expressions the route name must match to be included
  • exclude - an array of regular expression tht the route name must not match

Example: suppose you wanted to export you app and admin routes to separate files

JsonRoutesWebpack.configure do |config|
  config.add_routes 'app/javascript/routes/routes.json', exclude: [/admin/]
  config.add_routes 'app/javascript/routes/admin_routes.json', include: [/admin/]
end

Configure Rake to build json routes before Webpacker compiles

We need the json routes to be available to webpack loaders add a rake hook to build the routes before Webpacker compiles our javascript

lib/tasks/js_routes.rake

# generate json routes before webpacker so they can be used by loaders
if Rake::Task.task_defined?("webpacker:compile")
  Rake::Task["webpacker:compile"].enhance ["json_routes_webpack:compile"]
end

Install js-routes-loader and configure Webpacker to use it for routes json files

$ yarn add js-routes-loader

config/webpack/environment.js

const { environment } = require('@rails/webpacker');

environment.loaders.set('js-routes', {
  test: /routes\.json$/,
  use: 'js-routes-loader',
});

module.exports = environment;

License

The gem is available as open source under the terms of the MIT License.