3

I try to get the path information as follows:

  const typeChecker = program.getTypeChecker();
  const importFileSymbol = typeChecker.getSymbolAtLocation(
    importDeclarationNode.moduleSpecifier
  );
  const path = importFileSymbol?.valueDeclaration?.path || '';

In this way, I can get the sourceFile object of the module source file, and get the absolute path of the module through the path attribute on sourceFile. But path is an internal property of typescript and does not expose the type, so I think there may be some problems with this usage.

So I wonder if there is any other way to get it?

I also tried to get it through the fileName property of sourceFile, but for modules imported through path mapping, the obtained path is not an absolute path。

1
  • 1
    You should be able to get it from sourceFile.fileName if the compiler host always ensures that source files are created with an absolute path. Apr 14, 2022 at 19:46

1 Answer 1

3

I haven't done it exactly as you're trying to parse it, but I was able to use the resolveModuleName method in the typescript API to accomplish what you're asking, following the docs here

import * as fs from 'fs';
import * as ts from 'typescript';

function resolvePathsToModuleImports(typescriptFilePath: string) {
    // To use the typescript module resolution, you need to get the tsconfig
    // Here we assume you already have a reference to the tsconfig JSON
    const tsConfigObject = ts.parseJsonConfigFileContent(
        TSCONFIG_JSON_CONTENT,
        ts.sys,
        PATH_TO_BASE_OF_PROJECT
      );

    const fileContent = fs.readFileSync(typescriptFilePath).toString();
    // Preprocess the typescript file using the compiler API
    // to get the raw imports as represented in the file
    const fileInfo = ts.preProcessFile(fileContent);

    // You can then get the file path, etc, by resolving the imports via the
    // compiler API
    fileInfo.importedFiles
        .map(importedModule => importedModule.fileName)
        .forEach(rawImport => {
            const resolvedImport = 
                ts.resolveModuleName(
                    rawImport, 
                    typescriptFilePath, 
                    tsConfigObject.options, 
                    ts.sys);
            // Depending on how fancy your ts is, the
            // "resolvedImport.resolvedModule.resolvedFileName" may not exist,
            // but should resolve for all ts files
            const importLoc = resolvedImport.resolvedModule.resolvedFileName;
            console.log(`File ${typescriptFilePath} imports ${rawImport} from location ${importLoc}`);
        });
}



3
  • How do you run this file? I tried everything using ts-node, esm node option, trying to tsc this file ...etc and nothing worked. Sorry to ask, it is the first time i need to write a script using typescript api. I need to write a script which will check every ts files in the project and replace all the barrels imports by direct file path import (to fix poor jest performance with barrels since jest esm is nearly impossible to get it work) Thanks in advance!
    – Remi C
    May 31, 2022 at 13:37
  • So i managed to make it work using mjs extension. But when for instance an interface Test is imported from the ts file from a barrel file, the path retrieved will be the one of the barrel file, not the full path where the interface Test is.
    – Remi C
    May 31, 2022 at 14:16
  • I'm running it as part of a node script. I pushed a skeleton of the setup I'm using here, you should just be able to drop the function in there and invoke it in the main.ts: github.com/denalisk/typescript-node-skeleton
    – denalisk
    Jun 6, 2022 at 22:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.