Skip to content

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.

1 participant