Rails have long co-existed with Javascript through a variety of ways. As the Javascript ecosystem grows more powerful and complex each day, finding a better way to make Javascript a first-class citizen in the Rails world has become compelling. Rails 5.1 will officially comes with Webpack through the Webpacker gem, but you don't have to wait for that. You can use Webpacker with Rails 4.2+ today. We describe briefly how Javascript existed in the Rails world, and the jump straight into creating a simple Rails/Javascript app from scratch in less 3 minutes.
29. app/javascript/simple/index.js
import _ from 'lodash';
function component () {
var element = document.createElement('div');
/* lodash is required for the next line to work */
element.innerHTML = _.join(['Woohoo','webpack'], ' ');
return element;
}
document.body.appendChild(component());
32. Bundle Output
Where JS code lives
Bundle entry points
Refers to code
/public/packs
Outputs to
Webpack config
33. public/packs/simple.js
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
....
function component() {
var element = document.createElement('div');
/* lodash is required for the next line to work */
element.innerHTML =
__WEBPACK_IMPORTED_MODULE_0_lodash___default.a.join(['Woohoo',
'webpack'], ' ');
return element;
}
40. Webpack Wrappers
Where JS code lives
Bundle entry points
Refers to code
/public/packs
Outputs to
Webpack config
Webpack
Wrappers
41. Webpack Wrapper (cont.)
● bin/webpack
○ Compiling bundles
● bin/webpack-watcher
○ Watch for bundle changes and re-compile with Webpack into public/packs
● bin/webpack-dev-server
○ Live-reloading
■ Watch for bundle changes, re-compile with Webpack, and refresh
■ Can serve pages from public/packs
Manual compile (e.g., production deploy): rails webpack:compile