TL;DR: A little bit changes to the options of the Project
constructor will greatly reduce the time consuming during the initializing of the new instance.
const project = new Project({
tsConfigFilePath,
manipulationSettings,
// **The real problem here**
// Should set to false and add files needed manually
addFilesFromTsConfig: false,
// Can reduce a chunk of time if added alone without other options
skipFileDependencyResolution: true,
// Not important, but a better-have theoreticallly
compilerOptions: { isolatedModules: true },
});
In most daily cases, imports organizing only deal with files on a one-to-one basis. There is no need to know the whole detail of the project(s), nor the dependency relations of every single file. The only thing wo do need is the pure AST.
Currently, the default options of the Project
constructor, which defined by ts-morph
, is quite opposite to our ideal scenario:
https://github.com/dsherret/ts-morph/blob/e769b7871982ca874684e20355d58f1153efdcda/packages/ts-morph/src/Project.ts#L11-L34
FYI, we use organize-imports-cli
in a middle size project, managed by lerna
, with dozens of inline packages. That means, when commited files scatter acrose several packages, each package will produce an instance of Project
, and each instance costs 3 seconds on average, because ts-morph
is trying to load all the files during initializing, though most of them are totally irrelevant.
I have tried modify the code locally, and passed all the tests, except the excluded test
, which is caused by addFilesFromTsConfig
. So if you are willing to alter the options, there will be some more effort needed to deal with file resolving when included files defined in the tsconfig.json
are really all needed. But for almost all daily cases, it will just works fine.