npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ts-morph/bootstrap

v0.25.0

Published

API for getting quickly set up with the TypeScript Compiler API.

Downloads

581,036

Readme

@ts-morph/bootstrap

npm version CI

A library for quickly getting set up with the TypeScript Compiler API.

This library is separate from ts-morph, but uses some of its underlying infrastructure.

Example

import { createProject, ts } from "@ts-morph/bootstrap";

const project = await createProject(); // or createProjectSync

// these are typed as ts.SourceFile
const myClassFile = project.createSourceFile(
  "MyClass.ts",
  "export class MyClass { prop: string; }",
);
const mainFile = project.createSourceFile(
  "main.ts",
  "import { MyClass } from './MyClass'",
);

// ts.Program
const program = project.createProgram();
// ts.TypeChecker
const typeChecker = program.getTypeChecker();
// ts.LanguageService
const languageService = project.getLanguageService();
// ts.ModuleResolutionHost
const moduleResolutionHost = project.getModuleResolutionHost();

Setup

Generally:

const project = await createProject({ tsConfigFilePath: "tsconfig.json" });

Or use the synchronous API:

const project = createProjectSync({ tsConfigFilePath: "tsconfig.json" });

File Systems

// will use a real file system
const project = await createProject();

// in memory file system
const project2 = await createProject({ useInMemoryFileSystem: true });

// custom file system
const fileSystem: FileSystemHost = { ...etc... };
const project = await createProject({ fileSystem });

To access the file system after creating a project, you can use the fileSystem property:

project.fileSystem.writeFileSync("MyClass.ts", "class MyClass {}");

Compiler options

const project = await createProject({
  compilerOptions: {
    target: ts.ScriptTarget.ES3,
  },
});

tsconfig.json:

If you would like to manually specify the path to a tsconfig.json file then specify that:

const project = await createProject({
  tsConfigFilePath: "packages/my-library/tsconfig.json",
});

// output all the source files that were added
console.log(project.getSourceFiles().map(s => s.fileName));

Note: You can override any tsconfig.json options by also providing a compilerOptions object.

For your convenience, this will automatically add all the associated source files from the tsconfig.json. If you don't wish to do that, then you will need to explicitly set skipAddingFilesFromTsConfig to true:

const project = await createProject({
  tsConfigFilePath: "path/to/tsconfig.json",
  skipAddingFilesFromTsConfig: true,
});

Custom Module Resolution

Custom module resolution can be specified by providing a resolution host factory function. This also supports providing custom type reference directive resolution.

For example:

import { createProject, ts } from "@ts-morph/bootstrap";

// This is deno style module resolution.
// Ex. `import { MyClass } from "./MyClass.ts"`;
const project = await createProject({
  resolutionHost: (moduleResolutionHost, getCompilerOptions) => {
    return {
      resolveModuleNames: (moduleNames, containingFile) => {
        const compilerOptions = getCompilerOptions();
        const resolvedModules: ts.ResolvedModule[] = [];

        for (const moduleName of moduleNames.map(removeTsExtension)) {
          const result = ts.resolveModuleName(
            moduleName,
            containingFile,
            compilerOptions,
            moduleResolutionHost,
          );

          if (result.resolvedModule)
            resolvedModules.push(result.resolvedModule);
        }

        return resolvedModules;
      },
    };

    function removeTsExtension(moduleName: string) {
      if (moduleName.slice(-3).toLowerCase() === ".ts")
        return moduleName.slice(0, -3);
      return moduleName;
    }
  },
});

Adding Source Files

Use the following methods:

  • const sourceFiles = await project.addSourceFilesByPaths("**/*.ts"); or provide an array of file globs.
  • const sourceFile = await project.addSourceFileAtPath("src/my-file.ts"); or use addSourceFileAtPathIfExists(filePath)
  • const sourceFiles = await project.addSourceFilesFromTsConfig("path/to/tsconfig.json")

Or use the corresponding -Sync suffix methods for a synchronous API (though it will be much slower).

Creating Source Files

Use the Project#createSourceFile method:

const sourceFile = project.createSourceFile("MyClass.ts", "class MyClass {}");

Updating a Source File

Use the Project#updateSourceFile method. This can be provided a file path and string for the text or a new ts.SourceFile object:

const newSourceFile = project.updateSourceFile("MyClass.ts", "class MyClass {}");
// or
project.updateSourceFile(newSourceFileObj);

Removing a Source File

Use the Project#removeSourceFile method:

project.removeSourceFile("MyClass.ts");
// or
project.removeSourceFile(sourceFile);

Formatting Diagnostics

import { createProject, ts } from "@ts-morph/bootstrap";

const project = await createProject({ useInMemoryFileSystem: true });
project.createSourceFile("test.ts", "const t: string = 5;");

const program = project.createProgram();
const diagnostics = ts.getPreEmitDiagnostics(project.createProgram());

console.log(project.formatDiagnosticsWithColorAndContext(diagnostics));