Module: TypeScript::Node

Defined in:
lib/typescript-node.rb,
lib/typescript-node/version.rb,
lib/typescript-node/compile_result.rb

Defined Under Namespace

Classes: CompileResult

Constant Summary collapse

VERSION =
'1.1.0'

Class Method Summary collapse

Class Method Details

.check_nodeObject



84
85
86
87
88
89
# File 'lib/typescript-node.rb', line 84

def check_node
  unless locate_executable(node)
    raise "typescript-node requires node command, but it's not found. Please install it. " +
        "Set TS_NODE environmental variable If you want to use node command in non-standard path."
  end
end

.compile(source, *tsc_options) ⇒ String

Compile TypeScript to JavaScript.

Parameters:

  • source (String)

    TypeScript to be compiled

Returns:

  • (String)

    Resulted JavaScript



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/typescript-node.rb', line 46

def compile(source, *tsc_options)
  js_file = Tempfile.new(["typescript-node", ".ts"])
  begin
    js_file.write(source)
    js_file.close
    result = compile_file(js_file.path, *tsc_options)
    if result.success?
      result.js
    else
      raise result.stderr
    end
  ensure
    js_file.unlink
  end
end

.compile_file(source_file, *tsc_options) ⇒ TypeScript::Node::CompileResult

Compile TypeScript source file.

Parameters:

  • source_file (String)

    TypeScript source file

Returns:



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/typescript-node.rb', line 28

def compile_file(source_file, *tsc_options)
  Dir.mktmpdir do |output_dir|
    output_file = File.join(output_dir, "out.js")
    exit_status, stdout, stderr = tsc(*tsc_options, '--out', output_file, source_file)

    output_js = File.exists?(output_file) ? File.read(output_file) : nil
    CompileResult.new(
        output_js,
        exit_status,
        stdout,
        stderr,
    )
  end
end

.locate_executable(cmd) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/typescript-node.rb', line 68

def locate_executable(cmd)
  if RbConfig::CONFIG["host_os"] =~ /mswin|mingw/ && File.extname(cmd) == ""
    cmd << ".exe"
  end

  if File.executable? cmd
    cmd
  else
    path = ENV['PATH'].split(File::PATH_SEPARATOR).find { |p|
      full_path = File.join(p, cmd)
      File.executable?(full_path) && File.file?(full_path)
    }
    path && File.expand_path(cmd, path)
  end
end

.nodeObject

node command TS_NODE environmental variable is used when it is set.



64
65
66
# File 'lib/typescript-node.rb', line 64

def node
  ENV["TS_NODE"] || "node"
end

.tsc(*args) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/typescript-node.rb', line 17

def tsc(*args)
  cmd = [node, Src.tsc_path.to_s, *args]
  Open3.popen3(*cmd) do |stdin, stdout, stderr, wait_thr|
    stdin.close
    [wait_thr.value, stdout.read, stderr.read]
  end
end

.tsc_versionObject



12
13
14
# File 'lib/typescript-node.rb', line 12

def tsc_version
  TypeScript::Src.version
end