我正在尝试使用 Typescript API 进行一些自定义编译(使用插件等)。
使用命令行编译时,typescript 不仅会自动考虑 compilerOptions,还会自动考虑 excludes
键,以及 types
键(除其他外)。
Typescript API 文档几乎不存在,但我尝试手动进行深度搜索并将这些文件从传递给 createProgram
的总文件列表中排除。方法。然而,这对我们的构建性能造成了影响,我认为 Typescript 编译器有一个更有效的解决方案。
这是我的 compile.ts
中的内容文件。
import ts from 'typescript';
import keysTransformer from 'ts-transformer-keys/transformer';
import tsConfig from './tsconfig.json';
import fs from 'fs';
const deepFindTsFiles = (dir: string, fileList?: string[]) => {
dir = dir.endsWith('/') ? dir : dir + '/'
const files = fs.readdirSync(dir);
fileList = fileList || [];
files.forEach((file) => {
console.log('file', dir + file);
console.log(tsConfig.exclude.includes(dir + file));
if (fs.statSync(dir + file).isDirectory() && !tsConfig.exclude.includes(dir + file)) {
fileList = deepFindTsFiles(dir + file + '/', fileList);
}
else if (!tsConfig.exclude.includes(dir + file) && file.split('.')[1].includes('ts')) {
fileList!.push(dir + file);
}
});
return fileList;
};
const fileList = deepFindTsFiles(tsConfig.compilerOptions.rootDir);
// the compiler options parsed from tsconfig.json
const { options } = ts.parseJsonConfigFileContent(
tsConfig,
ts.sys,
__dirname
);
// createProgram doesn't seem to have an option for excludes/includes/types
const program = ts.createProgram(fileList, options);
const transformers = {
before: [keysTransformer(program)],
after: []
};
program.emit(undefined, undefined, undefined, false, transformers);
上面的代码正确编译了我的源代码并应用了正确的插件,但是它比使用命令行工具慢得多。
传入
createProgram
的内容方法只是我的 tsconfig.json 文件中的 compilerOptions 对象,而不是要排除的文件。好像不是createProgram
方法接受任何这样的参数。但是,肯定有吗?对?我不得不想象这是可能的。但是,文档严重缺乏
最佳答案
我设法弄清楚如何使用 tsconfig.json 和 TS 编译器 API 获取文件名列表。
const configPath = ts.findConfigFile(
"./", /*searchPath*/
ts.sys.fileExists,
"tsconfig.json"
);
if (!configPath) throw new Error("Could not find a valid 'tsconfig.json'.");
const configFile = ts.readJsonConfigFile(configPath, ts.sys.readFile);
const { fileNames } = ts.parseJsonSourceFileConfigFileContent(
configFile,
ts.sys,
'./'
);
console.log(fileNames)
这考虑了 tsconfig.json 中指定的包含和排除。
这可能不是最好的方法,但我一直在努力解决这个问题。
关于node.js - 你能在 Typescript Compiler API 中引入 excludes/includes 选项吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57333825/