Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support tsConfig paths aliases during move operations #1495

Open
wants to merge 1 commit into
base: latest
Choose a base branch
from

Conversation

tryggvigy
Copy link

Showcases fix for #1494.

Naive support for tsconfig.compilerOptions.paths module specifier aliases during move operations.

const project = new Project({
  useInMemoryFileSystem: true,
  compilerOptions: {
    paths: {
      'Root/*': ['./*']
    }
  }
});

const a = project.createSourceFile("a.ts", `export function foo() {}`);
// b.ts imports `a` via paths mapping alias.
const b = project.createSourceFile("b.ts", `import { foo } from "Root/a";`);

// Move ./a.ts -> ./a./a.ts
const dir = project.createDirectory('./a');
a.moveToDirectory(dir);

// Updating path aliased import works.
expect(b.getFullText()).to.equal(`import { foo } from "Root/a/a";`);

Comment on lines +1028 to +1044
const paths = compilerOptions?.paths;
// See https://www.typescriptlang.org/docs/handbook/modules/reference.html#paths
if (paths) {
// Check if the string literal is a path alias specifier
for (const [path, mappings] of Object.entries(paths)) {
const hasWildCard = path.endsWith('*');
const [alias] = path.split('*');
if (literalText.startsWith(alias) && hasWildCard) {
const pathAfterAlias = FileUtils.pathJoin(
stringLiteral._sourceFile.getDirectoryPath(),
stringLiteral._sourceFile.getRelativePathAsModuleSpecifierTo(sourceFile)
);
stringLiteral.setLiteralValue(FileUtils.pathJoin(alias, pathAfterAlias));
break;
}
}
}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is very naive right now and only works with wildcard paths (most common use-case afaik). If we want to productionize this approach we should create new helpers in ModuleUtils and/or SourceFile to more deeply support paths aliases, instead of reaching directly for FileUtils here.

compilerOptions: {
baseUrl: '.',
paths: {
'Root/*': ['./*']
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we want to move ahead with this PR we should add a lot more tests for paths.

  • With and without wildcard value
  • More nested mappings

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant