Skip to content

Commit c941c2a

Browse files
committed
feat: remove unused commonjs imports
1 parent f9cd69e commit c941c2a

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

build.go

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,14 +32,19 @@ func relativeFilePath(a, b string) (r string, e error) {
3232
return
3333
}
3434

35-
func commonJSImports(conf *config.Config, c *code, tsFilename string) {
35+
func commonJSImports(conf *config.Config, c *code, tsFilename string, code string) {
3636
packageNames := make([]string, 0, len(conf.Mappings))
3737
for packageName := range conf.Mappings {
3838
packageNames = append(packageNames, packageName)
3939
}
4040
sort.Strings(packageNames)
4141
for _, packageName := range packageNames {
4242
importMapping := conf.Mappings[packageName]
43+
44+
if len(code) > 0 && !strings.Contains(code, importMapping.TypeScriptModule+".") {
45+
continue
46+
}
47+
4348
relativePath, relativeErr := relativeFilePath(tsFilename, importMapping.Out)
4449
if relativeErr != nil {
4550
fmt.Println("can not derive a relative path between", tsFilename, "and", importMapping.Out, relativeErr)
@@ -141,10 +146,12 @@ func Build(conf *config.Config, goPath string) { //nolint:maintidx
141146
_, _ = fmt.Fprintln(os.Stderr, " could not generate ts code", err)
142147
os.Exit(3)
143148
}
144-
tsClientCode := newCode(" ")
145-
commonJSImports(conf, tsClientCode, target.Out)
146-
tsClientCode.l("").l("")
147-
ts = tsClientCode.string() + ts
149+
150+
// workaround to remove unneeded imports
151+
importsCode := newCode(" ")
152+
commonJSImports(conf, importsCode, target.Out, ts)
153+
importsCode.l("").l("")
154+
ts = importsCode.string() + ts
148155

149156
// _, _ = fmt.Fprintln(os.Stdout, ts)
150157
updateErr := updateCode(target.Out, getTSHeaderComment()+ts)
@@ -238,8 +245,6 @@ func Build(conf *config.Config, goPath string) { //nolint:maintidx
238245
moduleCode := newCode(" ")
239246
structIndent := -3
240247

241-
commonJSImports(conf, moduleCode, mapping.Out)
242-
243248
var structNames []string
244249

245250
for structName := range mappedStructsMap {
@@ -254,7 +259,14 @@ func Build(conf *config.Config, goPath string) { //nolint:maintidx
254259
}
255260

256261
moduleCode.l("// end of common js")
257-
updateErr := updateCode(mapping.Out, getTSHeaderComment()+moduleCode.string())
262+
263+
// workaround to remove unneeded imports
264+
importsCode := newCode(" ")
265+
commonJSImports(conf, importsCode, mapping.Out, moduleCode.string())
266+
importsCode.l("").l("")
267+
ts := importsCode.string() + moduleCode.string()
268+
269+
updateErr := updateCode(mapping.Out, getTSHeaderComment()+ts)
258270
if updateErr != nil {
259271
_, _ = fmt.Fprintln(os.Stderr, " failed to update code in", mapping.Out, updateErr)
260272
}

0 commit comments

Comments
 (0)