-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
import.ts
111 lines (102 loc) · 2.41 KB
/
import.ts
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
55
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import {
ColiBuilder,
BaseImportSpecifier,
ImportDeclaration,
ImportDefaultSpecifier,
ImportSpecifier,
} from "@coli.codes/core";
/**
* A Import Builder with builder pattern.
*
* **Usage**
*
* 1. `Import.declare(...)`
* 2. `new Import().import(...).from(...)`
* 3. `new Import().import(...).from(...).make()`
*/
export class Import extends ColiBuilder<ImportDeclaration> {
private source: string;
private default: ImportDefaultSpecifier;
private m_import: ImportSpecifier;
private imports: ImportSpecifier[] = [];
static declare(source: string): ImportDeclaration {
return new ImportDeclaration({
source: source,
});
}
from(source: string): this {
this.source = source;
return this;
}
/**
* set single import default specifier. calling this multiple times will override previous call effect.
*
* e.g.
*
* 1. `import a from "a"`
* 2. ~~import `{ a }` from "a"~~ **(NOT THIS)**
* @param local
* @returns
*/
importDefault(local: string): this {
this.default = new ImportDefaultSpecifier({
local: local,
});
return this;
}
/**
* adds `{?}` import
*
* e.g.
*
* 1. import `{ a }` from "a"
* 2. ~~import a from "a"~~ **(NOT THIS)**
* @param _import
* @returns
*/
import(_import: HandyImport): this {
this.m_import = handyImportToImportSpecifier(_import);
return this;
}
/**
* add more import. same as `.import(...)`
* @param _import
* @returns
*/
and(..._import: HandyImport[]): this {
_import.forEach((e) => {
this.imports.push(handyImportToImportSpecifier(e));
});
return this;
}
private get specifiers(): BaseImportSpecifier[] {
const final = [];
this.default && final.push(this.default);
this.m_import && final.push(this.m_import);
final.push(...this.imports);
return final;
}
__finalize(): ImportDeclaration {
return new ImportDeclaration({
specifiers: this.specifiers,
source: this.source,
});
}
}
/**
* specifies import
* e.g.
*
* 1. import `{ a }` from "a"
* 2. import `{a as _}` from "a"
*/
type HandyImport = { import: string; as?: string } | string;
function handyImportToImportSpecifier(_import: HandyImport): ImportSpecifier {
if (typeof _import == "string") {
return new ImportSpecifier({
import: _import,
});
} else if (typeof _import == "object") {
return new ImportSpecifier(_import);
}
}