Sha256: 2a80281ee84e76e4bfe354a6c433997d20bf70a1382326cb0e96f5cdbd5e7dd8

Contents?: true

Size: 1.16 KB

Versions: 1

Compression:

Stored size: 1.16 KB

Contents

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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
roli-sprockets-commonjs-0.0.10 lib/sprockets/commonjs.rb