Module: TypeScript

Defined in:
lib/ruby-typescript.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
'0.1.1'

Class Method Summary collapse

Class Method Details

.compile_file(filepath, options = {}) ⇒ Object

Compiles a TypeScript file to JavaScript.

Parameters:

  • filepath (String)

    the path to the TypeScript file

  • options (Hash) (defaults to: {})

    the options for the execution

Options Hash (options):

  • :output (String)

    the output path

  • :source_map (Boolean)

    create the source map or not

  • :module (String)

    module type to compile for (commonjs or amd)

  • :target (String)

    the target to compile toward: ES3 (default) or ES5



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/ruby-typescript.rb', line 56

def compile_file(filepath, options={})
  options = options.clone
  if not options[:output]
    options[:output] = filepath.gsub(/\.ts$/, '.js')
  end
  output_filename = options[:output]
  args = [filepath] + flatten_options(options)
  stdout, stderr, wait_thr = node_compile(*args)

  if wait_thr.nil?
    success = stdout.empty? and stderr.empty?
  else
    success = wait_thr.value == 0
  end

  if success
    result = {
      :js => output_filename,
      :stdout => stdout,
    }
    if options[:source_map]
      result[:source_map] = output_filename + '.map'
    end
    return result
  else
    raise TypeScript::Error, ( stderr.empty? ? stdout : stderr )
  end
end

.flatten_options(options) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/ruby-typescript.rb', line 26

def flatten_options(options)
  args = []
  if options[:output]
    args << '--out' << options[:output]
  end

  if options[:source_map]
    args << '--sourceMap'
  end
  
  if options[:module]
    args << '--module' << options[:module]
  end
  
  if options[:target]
    args << '--target' << options[:target]
  end

  return args
end

.node_compile(*args) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/ruby-typescript.rb', line 14

def node_compile(*args)
  if typescript_path
    cmd = [typescript_path] + args
  else
    cmd = ['tsc'] + args
  end
  cmd = cmd.join(' ')
  stdin, stdout, stderr, wait_thr = Open3.popen3(cmd)
  stdin.close
  [stdout.read, stderr.read, wait_thr]
end

.typescript_pathObject



10
11
12
# File 'lib/ruby-typescript.rb', line 10

def typescript_path
  ENV['TYPESCRIPT_SOURCE_PATH']
end