require "sprockets" require "tilt" module Sprockets class CommonJS < Tilt::Template EXTENSIONS = %w(.module .cjs).freeze class << self attr_accessor :default_namespace end self.default_mime_type = "application/javascript" self.default_namespace = "this.require" protected def prepare @namespace = self.class.default_namespace end def evaluate(scope, _locals, &_block) if commonjs_module?(scope) scope.require_asset "sprockets/commonjs" wrap_code(namespace, module_name(scope), data) else data end end private attr_reader :namespace def wrap_code(ns, name, code) "#{ns}.define({#{name}:function(exports, require, module){#{code};}});\n" end def commonjs_module?(scope) EXTENSIONS.include?(File.extname(scope.logical_path)) end def module_name(scope) scope.logical_path .gsub(%r{\A\.?/}, "") # Remove relative paths .chomp(".module") # Remove module ext .inspect end end register_postprocessor "application/javascript", CommonJS append_path File.expand_path("../../../assets", __FILE__) end