I implemented a lot of web applications using Rails. I find it very easy to work with Ruby and Rails to create API and write server business logic. For the client side though I do not like to depend so much on Rails and I prefer to build interactive Single Page Application where the communication with server side is done via API. For this use case I find Rails sprockets not appropriate and not easy to use. It’s not ready for ES6/ES7 also. Although there are gems that can convert from ES6 to ES5 like this one sprockets-es6 it does not support node module system and packaging like webpack does.
The reason I keep JS application inside Rails and do not deploy it separately as a standalone application only because of the authentication. I do not see any good solution to protect a SPA application besides using oauth2 via hello.js with client side authentication. So I usually keep client application inside Rails and protected them with Devise and oauth2. Authentication is done by rails, if the user is not authenticated the client side application is not loaded at all.
In this post I explain how to configure a new rails application to work as above.
First we need to add webpack-assets gem in Gemfile.
Then we need to create a webpack.config.js file inside Rails root or generate it with this command:
This is my configuration file I use in current project:
In development mode run webpack watch to create the bundle and update it on every change:
Now the client side application is decoupled from Rails, only the final bundled file is imported in rails. One thing I recommend to be able to let React router handle the routes and not Rails is to add this line in routes.rb:
This will send all the request to same page and let react router handle the paths.