-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathcommon.ex
More file actions
54 lines (42 loc) · 1.33 KB
/
common.ex
File metadata and controls
54 lines (42 loc) · 1.33 KB
1
2
3
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
45
46
47
48
49
50
51
52
53
54
defmodule ElixirScript.ModuleSystems.Common do
@moduledoc false
alias ESTree.Tools.Builder, as: JS
alias ElixirScript.Translator
alias ElixirScript.Translator.State
alias ElixirScript.Translator.Utils
def build(imports, js_imports, body, exports) do
module_imports = Enum.map(imports, fn {module, path} -> import_module(module, path) end)
imports = js_imports
|> Enum.map(fn
{module, path} -> import_module(module, path)
{module, path, _} -> import_module(module, path)
end)
imports = Enum.uniq(imports ++ module_imports)
export = if is_nil(exports), do: [], else: [export_module(exports)]
imports ++ body ++ export
end
defp import_module(module_name, from) do
js_module_name = ElixirScript.Translator.Identifier.make_namespace_members(module_name)
do_import_module(js_module_name, from)
end
defp do_import_module(ref, file_path) do
ref_declarator = JS.variable_declarator(
ref,
JS.call_expression(
JS.identifier("require"),
[JS.literal(file_path)]
)
)
JS.variable_declaration([ref_declarator], :const)
end
defp export_module(exported_object) do
JS.assignment_expression(
:=,
JS.member_expression(
JS.identifier("module"),
JS.identifier("exports")
),
exported_object
)
end
end