Module: TypeScript

Defined in:
lib/ruby-typescript.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
'0.1.2'

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

  • :output_dir (Boolean)

    the directory to output files to

  • :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



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/ruby-typescript.rb', line 62

def compile_file(filepath, options={})
  options = options.clone
  if options[:output]
    output_filename = options[:output]
  elsif options[:output_dir]
    filename = File.basename(filepath).gsub(/[.]ts$/, '.js')
    output_filename = File.join(options[:output_dir], filename)
  else
    output_filename = filepath.gsub(/[.]ts$/, '.js')
  end

  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



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

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

  if options[:output_dir]
    args << '--outDir' << options[:output_dir]
  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



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

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



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

def typescript_path
  ENV['TYPESCRIPT_SOURCE_PATH']
end