Skip to content

Instantly share code, notes, and snippets.

@xthezealot
Created July 30, 2025 20:30
Show Gist options
  • Save xthezealot/b5afb8b7393b16b7246e10b912a42a22 to your computer and use it in GitHub Desktop.
Save xthezealot/b5afb8b7393b16b7246e10b912a42a22 to your computer and use it in GitHub Desktop.
Middleman Opal extension
require_relative "lib/middleman_opal_extension"
activate :opal
activate :autoprefixer do |prefix|
prefix.browsers = "last 2 versions"
end
configure :development do
activate :livereload
end
configure :build do
activate :minify_css
activate :minify_javascript, compressor: Terser.new
end
require "middleman-core"
require "opal"
require "tilt"
# custom Tilt template for Opal Ruby-to-JavaScript compilation
class Tilt::OpalTemplate < Tilt::Template
def self.engine_initialized?
defined? ::Opal
end
def initialize_engine
require "opal"
end
def evaluate(scope, locals, &block)
begin
# create Opal builder
builder = Opal::Builder.new
# add all Opal paths
Opal.paths.each { |path| builder.append_paths(path) }
# add the source directory containing the file
builder.append_paths(File.dirname(file))
# compile the Ruby code
result = builder.build_str(data, file)
result.to_s
rescue => e
"/* Opal compilation error in #{file}: #{e.message} */"
end
end
def allows_script?
false
end
end
class MiddlemanOpalExtension < ::Middleman::Extension
def initialize(app, options_hash = {}, &block)
super
# register the Opal template handler with Tilt
::Tilt.register(Tilt::OpalTemplate, "js.rb")
end
end
# register the extension
::Middleman::Extensions.register(:opal, MiddlemanOpalExtension)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment