dsherret / dsherret/ts-morph

Convenient method to avoid adding named imports multiple times

Open
#1,184 1 comment 0 reactions 0 assignees View on GitHub
suggestion
Dominant language
TypeScript
Stars
6.2k
Forks
238
Avg merge
2m
Merged PRs (30d)
1

Description

**Is your feature request related to a problem? Please describe.**

Thanks for ts-morph!!!

I'm generating code, and I'd like a quick way to avoid adding a named import multiple times.

It's possible to check for imports via `getDeclaration()`:

```
// given a name (named import) and a path
if (!sourceFile.getImportDeclaration(path)) {
sourceFile.addImportDeclaration({moduleSpecifier: path, namedImports: [name]})
```

I'd like to go a step further and make sure the named import isn't already added by doing

```
if (!sourceFile.getImportDeclaration(path).getNamedImports(name))
sourceFile.addImportDeclaration({moduleSpecifier: path, namedImports: [name]})
```

I couldn't see how to make a dummy `ImportSpecifier` to search with `Array.includes()` on the result of `getNamedImports()` but I assume it's an internal class which makes sense.

**Describe the solution you'd like**

Maybe a way to ask of a `"name"` or `{name: "name", alias: "alias"}` is already declared in the sourceFile?

**Describe alternatives you've considered**

The following works to prevent adding multiple times, but perhaps I'm missing something for it to be simpler (always learning with JS and TS):
```
const dcl = sourceFile.getImportDeclaration(path)
if (!dcl || dcl.getNamedImports().filter((n) => n.getName() === name).length === 0) {
sourceFile.addImportDeclaration({ moduleSpecifier: path, namedImports: [name] })
}
```

Contributor guide

Open the contributing guide

Research direction

Read CONTRIBUTING.md, then inspect the existing SourceFile APIs getImportDeclaration(), getNamedImports(), and addImportDeclaration() described in the issue. Define a convenient way to check whether a named import is already present, including the requested name or alias form, and verify that repeated additions are prevented.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.