Skip to content

Instantly share code, notes, and snippets.

@ireneybean
Created August 3, 2019 21:05
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ireneybean/8501ce93fa27684f137743ab5255187c to your computer and use it in GitHub Desktop.
Save ireneybean/8501ce93fa27684f137743ab5255187c to your computer and use it in GitHub Desktop.
Stimulus.js without a build system, but with babel, Sinatra
#...
get '/' do
haml :index, layout: false
end
#...
//app-js-src/es6/stimulus/hello_controller.js
(() => {
stimulus.register("hello", class extends Stimulus.Controller {
static get targets() {
return [ "name" ]
}
greet() {
console.log(`Hello, ${this.name}!`)
}
get name() {
return this.nameTarget.value
}
})
})()
# views/index.haml
!!!
%html
%head
%meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}/
%meta{:charset => "utf-8"}/
%script{:src => "/javascript/src/ext/stimulus.umd.js"}
%script{:src => "/javascript/src/lib/stimulus/init.js"}
%script{:src => "/javascript/src/lib/stimulus/hello_controller.js"}
%body
%div{"data-controller" => "hello"}
%input{"data-target" => "hello.name", :type => "text"}/
%button{"data-action" => "click->hello#greet"} Greet
//app-js-src/es6/stimulus/init.js
(function () {
if (!("stimulus" in window)) {
window.stimulus = Stimulus.Application.start();
}
})();
#...
desc 'Transpile javascript assets into bundles'
task :transpile do
require 'babel/transpiler'
options = { blacklist: ['useStrict'], comments: false }
srcfiles = Dir.glob('./app-js-src/es6/**/*.js')
srcfiles.map { |filepath| File.new(filepath) }.each do |srcfile|
es5_code = Babel::Transpiler.transform(srcfile.read, options)['code']
newpath = srcfile.path.split('/')[3..-1].join('/')
dirname = File.dirname("public/javascript/src/lib/#{newpath}")
unless File.directory?(dirname)
FileUtils.mkdir_p(dirname)
end
out_file = File.new("public/javascript/src/lib/#{newpath}", 'w')
out_file.puts(es5_code)
out_file.close
puts "TRANSPILED TO #{out_file.path}"
end
end
task default: %i[clean transpile]
end
#...
@ireneybean
Copy link
Author

ireneybean commented Aug 3, 2019

I'm sure there is a more elegant way to deal with the path manipulation in my rakefile, but since this was just a quick and dirty POC I didn't want to spend my time on optimizing that.

@ireneybean
Copy link
Author

Note to self: Define target names in your controller class using the static targets array:

// controllers/search_controller.js
import { Controller } from "stimulus"

export default class extends Controller {
static targets = [ "query", "errorMessage", "results" ]
// …
}
Note: You may need to enable support in your JavaScript environment for the static class properties standard (see @babel/plugin-proposal-class-properties).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment