dsherret / dsherret/ts-morph

leadingTrivia at the file level is not actually leading

Open
#1,467 0 comments 1 reaction 0 assignees View on GitHub
Dominant language
TypeScript
Stars
6.2k
Forks
238
Avg merge
2m
Merged PRs (30d)
1

Description

When declaring a new file with the `leadingTrivia` option, the comments are not added at the very top (= leading) section of the file.

Added imports will supersede the comments and comments will be bumped down.

Version: 20.0.0

**To Reproduce**

From [playground](https://awhitty.me/ts-morph-playground/#code/eyJpbnB1dHMiOlt7InBhdGgiOiJpbmRleC50cyIsImNvbnRlbnQiOiIvLyBGaWxlIGludGVudGlvbmFsbHkgbGVmdCBibGFuayJ9XSwidHJhbnNmb3JtIjp7InBhdGgiOiJ0cmFuc2Zvcm0udHMiLCJjb250ZW50IjoiaW1wb3J0IHsgUHJvamVjdCwgVmFyaWFibGVEZWNsYXJhdGlvbktpbmQgfSBmcm9tICd0cy1tb3JwaCc7XG5cbmV4cG9ydCBkZWZhdWx0IGZ1bmN0aW9uIHRyYW5zZm9ybShwcm9qZWN0OiBQcm9qZWN0KSB7XG4gIHByb2plY3QuZ2V0U291cmNlRmlsZSgnaW5kZXgudHMnKS5kZWxldGUoKVxuXG4gIGNvbnN0IGYgPSBwcm9qZWN0LmNyZWF0ZVNvdXJjZUZpbGUoJ2luZGV4LnRzJywge1xuICAgIGxlYWRpbmdUcml2aWE6ICcvLyB0cml2aWEnLFxuICB9KVxuXG4gIGYuYWRkSW1wb3J0RGVjbGFyYXRpb24oe1xuICAgICAgbW9kdWxlU3BlY2lmaWVyOiAndml0ZScsXG4gICAgICBuYW1lZEltcG9ydHM6IFsnZGVmaW5lQ29uZmlnJ10sXG4gIH0pXG5cbiAgZi5hZGRWYXJpYWJsZVN0YXRlbWVudCh7XG4gICAgZGVjbGFyYXRpb25LaW5kOiBWYXJpYWJsZURlY2xhcmF0aW9uS2luZC5Db25zdCxcbiAgICBkZWNsYXJhdGlvbnM6IFtcbiAgICAgICAge1xuICAgICAgICAgIG5hbWU6ICdjb25maWcnLFxuICAgICAgICAgIGluaXRpYWxpemVyOiAnMScsXG4gICAgICAgIH0sXG4gICAgXSxcbiAgfSlcbn07In19).

```ts
import { Project, VariableDeclarationKind } from 'ts-morph';

export default function transform(project: Project) {
project.getSourceFile('index.ts').delete()

const f = project.createSourceFile('index.ts', {
leadingTrivia: '// trivia',
})

f.addImportDeclaration({
moduleSpecifier: 'vite',
namedImports: ['defineConfig'],
})

f.addVariableStatement({
declarationKind: VariableDeclarationKind.Const,
declarations: [
{
name: 'config',
initializer: '1',
},
],
})
};
```

Result:

```ts
import { defineConfig } from "vite";

// trivia
const config = 1;
```

**Expected behavior**

Comments (trivia) to be added to the top of the file.

Contributor guide

Open the contributing guide

Research direction

Read CONTRIBUTING.md, then run the linked playground reproduction using createSourceFile with leadingTrivia followed by addImportDeclaration. Trace how the file-level trivia is positioned after the import is added, and consider the issue complete when the generated output keeps the comments at the very top of the file.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.