2

I'm trying to compile a full typescript project using the typescript compiler. What I got so far is that the files specified in the tsconfig.json file are compiled and available. However, I also want to access the files on which the project files are dependent on, so files in node_modules. But only the ones that are used by the files specified in the tsconfig.json file. How can I do that?

import * as fs from "fs"
import * as ts from "typescript"


function compile(fileNames: string[], options: ts.CompilerOptions): void {
    const createdFiles: { [key: string]: string } = {}
    const host = ts.createCompilerHost(options);
    host.writeFile = (fileName: string, contents: string) => {
        console.log(">>", fileName)
        createdFiles[fileName] = contents
    }

    const program = ts.createProgram(fileNames, options, host);
    program.emit();
}

const parseConfigHost /* : any */ = {
    fileExists: fs.existsSync,
    readDirectory: ts.sys.readDirectory,
    readFile: (file: string) => fs.readFileSync(file, 'utf8'),
    useCaseSensitiveFileNames: true,
}


const x = ts.parseJsonConfigFileContent(
    ts.readConfigFile('./tsconfig.json', ts.sys.readFile),
    parseConfigHost,
    ".",
)

compile(x.fileNames, x.options)
Corno
  • 5,448
  • 4
  • 25
  • 41
  • Just read the `node_modules` directory? I'm not sure what you mean. – kelsny Sep 22 '22 at 12:41
  • I updated my question. Is it clearer now? – Corno Sep 22 '22 at 18:09
  • I'm sorry, but isn't that still the entire `node_modules` directory? The folders in `node_modules` are all dependencies of your project. – kelsny Sep 22 '22 at 18:23
  • For compilation, only the .d.ts files are needed of the dependencies that are mentioned in the package.json file. Typically, there are much more modules in the node_modules directory than that. I Assume that the compiler is very much aware of which files are needed and which are not. It feels redundant to reimplement all this logic. – Corno Sep 24 '22 at 06:17

0 Answers0