Class: Ichiban::JSCompiler

Inherits:
Object
  • Object
show all
Defined in:
lib/ichiban/js_compiler.rb

Overview

This class uses source_map and uglifier to concatenate, minify, and source-map JS files.

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ JSCompiler

Returns a new instance of JSCompiler.



46
47
48
# File 'lib/ichiban/js_compiler.rb', line 46

def initialize(file)
  @file = file
end

Instance Method Details

#compileObject



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/ichiban/js_compiler.rb', line 4

def compile
  rel = @file.rel_to 'assets/js'
  Ichiban.config.js_manifests.each do |dest, sources|
    if sources.include? rel
      # Make the source paths absolute.
      sources = sources.map do |source|
        abs = File.join Ichiban.project_root, 'assets/js', source
        unless File.exists? abs
          raise "Something's wrong with Ichiban.config.js_manifests. JS source file does not exist: #{abs.inspect}"
        end
        abs
      end
      
      # Make two code strings. The first contains the minified JS. The second
      # contains the source map.
      js, map = compile_paths(
        sources,
        File.join(Ichiban.config.relative_url_root, 'js'),
        dest,
        dest + '.map'
      )
      
      # Make sure the JS folder exists.
      FileUtils.mkdir_p File.join(Ichiban.project_root, 'compiled/js')
      
      # Write the minified JS.
      compiled_js_path = File.join(Ichiban.project_root, 'compiled/js', dest)
      File.open(compiled_js_path, 'w') do |f|
        f << js
      end
      
      # Write the source map.
      File.open(File.join(Ichiban.project_root, 'compiled/js', dest + '.map'), 'w') do |f|
        f << map
      end
      
      # Log the compilation of the JS file, but don't log the compilation of the map.
      Ichiban.logger.compilation(@file.abs, compiled_js_path)
    end
  end
end