From Sprockets to Webpack
New pipeline option for Opal development
Problem
Normally in our Opal Ruby projects, we use Sprockets or Assets Pipeline to deliver front-end assets. This works fine when project is small back then.
However, what Sprockets do is concatenating all listed assets (maybe doing some transforming). This is hard to fit in the current era where a font-end application depending on tons of library which may have further more dependencies.
A single manifest approach to include all assets is not enough.
Why webpack?
webpack is a module bundler.
webpack takes modules with dependencies and generates static assets representing those modules.
It knows JS module system (either CommonJS or AMD) well, and provides awesome stuffs like bundling CSS, images, or support even transpiled languages like CoffeeScript, LESS, or Sass.
Webpack knows well about the stuff it generates. The flexible plugin system also makes it easy to write complex loader with custom logic (e.g. custom dependency resolution, source map concatenation).
As you can see, webpack looks like a nice fit to replace Sprockets.
Opal loader for webpack
Opal Ruby is not mysterious tech, it’s just a transpiler which let you write Javascript in Ruby. It should be simple and straightforward to integrate with webpack. (The loader is implemented around only 100 LOC).
So I develop opalrb-loader, an expeimental webpack loader to integrate Opal.
Let’s see how we can bootstrap a simple webpack setup.
Getting started
Install webpack first
npm install -g webpack
And install opalrb-loader
npm install opalrb-loader --save-dev
Now create a simple Ruby file
# main.rb
puts "From 1 to 10: #{10.times.to_a.join(',')}"
And a webpack config file (it’s just plain JS)
// webpack.config.js
module.exports = {
entry: 'opalrb-loader!./main.rb',
output: {
filename: 'bundle.js'
}
};
Boost it!
webpack
Yeah, now you can check out bundle.js to see the compiled code.
Can I still use Ruby Gems?
Definitely yes!
Since the loader doesn’t have implicit assumption on where to find Ruby source, it only looks up for environment variable named OPAL_LOAD_PATH.
This design makes the webpack packaging pipeline decoupled from any existing one. Thus enables the possibility to integrate with either Bundler or any other toolchain you choose.
Check out this example if you are curious on how this could be done.
Let’s sum up
I think integrating webpack is new to most Ruby/Rails developers. But it actually free us from the backend. Now we can use whatever backend we want and only embedding Opal Ruby in front-end.
Give it a try and tell me what you think!