Let’s understand how to exploit the Rails 5.1 and add Webpack to project. Before we start, webpacker has some prerequisites. It requires following:
- Ruby 2.2+
- Rails 4.2+
- Node.js 6.4.0+
- Yarn 0.20.1+
If all the prerequisites are satisfied then let’s create a rails application with webpack.
# Available Rails 5.1+ rails new myapp --webpack
Webpacker can be used with React, Vue, Angular, elm. So while creating a new application pass the required option.
# Rails 5.1+ rails new myapp --webpack=react rails new myapp --webpack=angular rails new myapp --webpack=vue rails new myapp --webpack=elm
This would create the basic rails application with webpack configured. Now if we look at the directory structure created. A new directory
app/packs would be created where
application.js would be the entry point for webpack assets.
application.js available to entire application. Add below code to
Similarly, if we want to add webpacker to the existing application. Follow these steps
# Add gem webpacker to Gemfile gem 'webpacker', '~> 2.0' # bundle bundle install # Within rails app ./bin/rake webpacker # If rails version < 5.0 ./bin/rails webpacker # If rails version > 5.0 # To add react for webpacker ./bin/rails webpacker:install:react
In the development environment, webpack require its own development server to compile assets so fire up the server in different terminals.
# Terminal 1 $ rails server # Terminal 2 $ ./bin/webpack-dev-server
If you’d rather not have to run the two processes separately by hand, you can use Foreman:
# Add foreman gem to Gemfile gem 'foreman', '~> 0.84.0' # Bundle bundle install # Add new Procfile in project directory and below content to the file web: bundle exec rails s webpacker: ./bin/webpack-dev-server # Start foreman to run both server foreman start
Webpack is configured to the rails app. To know more about the configuration in the production, development environment click here.