rnx-kit/packages/typescript-service
renovate[bot] 57013d2191
fix(deps): update eslint (major) (#3394)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Tommy Nguyen <4123478+tido64@users.noreply.github.com>
2024-10-17 14:41:52 +00:00
..
src fix: bump minimum Node version to 16.17 (#3339) 2024-09-10 18:02:14 +00:00
test test: migrate more tests to Node test runner (#3252) 2024-07-30 18:45:19 +02:00
CHANGELOG.md RELEASING: Releasing 44 package(s) (#3342) 2024-09-11 08:59:50 +02:00
README.md docs: automate removal of badges from READMEs (#2324) 2023-04-14 08:24:28 +02:00
eslint.config.js chore: migrate to ESLint flat config (#2782) 2023-11-03 14:02:18 +01:00
package.json fix(deps): update eslint (major) (#3394) 2024-10-17 14:41:52 +00:00
tsconfig.json feat(tsconfig): base TypeScript configs for working with Node (#2886) 2023-12-18 12:05:07 +01:00

README.md

@rnx-kit/typescript-service

Build npm version

@rnx-kit/typescript-service gives you access to TypeScript's language services, and lets you customize how module resolution occurs.

Configuration

The starting point for working with TypeScript is reading configuration from the command line, or from a configuration file like tsconfig.json.

Both methods yeild a ParedCommandLine object, offering the same level of control over how TypeScript behaves.

import ts from "typescript";

// Read configuration from a NodeJS command-line
const cmdLine = ts.parseCommandLine(process.argv.slice(2));

// Read configuration from a project file (parsed into a TypeScript command-line object)
const configFileName = findConfigFile(searchPath);
if (!configFileName) {
  throw new Error(`Failed to find config file under ${searchPath}`);
}
const cmdLine = readConfigFile(configFileName);
if (!cmdLine) {
  throw new Error(`Failed to read config file ${configFileName}`);
}

// For either method, handle errors
if (cmdLine.errors.length > 0) {
  ...
}

Language Services

TypeScript's language service allows you to work with source code continuously, unlike the TypeScript compiler, which makes a single pass through the code. The language service tends to load only what is needed to fulfill the current request, such as getting diagnostics for a particular source file, or re-loading a changed file being watched. This saves time and memory, when full source validation isn't needed.

The language service is accessible through the Service and Project classes. Service manages shared state across all projects, and is meant to be a singleton. Project contains a TypeScript configuration, which includes a list of source files. TypeScript configuration comes from either the command line or a file like tsconfig.json.

You can use a Project to validate code, and emit transpiled JavaScript:

const service = new Service();
const project = service.openProject(cmdLine);

// validate
const fileHasErrors = project.validateFile(fileName);
const projectHasErrors = project.validate();

// emit
const fileEmitted = project.emitFile(fileName);
const projectEmitted = project.emit();

You can also change which files are in a project. This is typically done in response to an external event, like a callback notifying you that a file has been added, updated or removed:

import ts from "typescript";

function onFileEvent(eventType: string, fileName: string, payload?: string) {
  if (eventType === "add") {
    project.addFile(fileName);
  } else if (eventType === "modify") {
    project.updateFile(
      fileName,
      payload && ts.ScriptSnapshot.fromString(payload)
    );
  } else if (eventType === "delete") {
    project.deleteFile(fileName);
  }
}

When you're finished working with a Project, you must dispose of it to properly release all internal resources:

project.dispose();

Customizing the Language Service

The language service is initialized using a host interface. You can customize the host interface to change the way TypeScript works:

const enhanceLanguageServiceHost = (host: ts.LanguageServiceHost): void => {
  // change host functions in here
};

const service = new Service();
const project = service.openProject(cmdLine, enhanceLanguageServiceHost);

For example, you can replace the functions which control how modules and type references are resolved to files:

function resolveModuleNames(
  moduleNames: string[],
  containingFile: string,
  reusedNames: string[] | undefined,
  redirectedReference: ResolvedProjectReference | undefined,
  options: CompilerOptions
): (ResolvedModule | undefined)[] {
  /* ... */
}

function resolveTypeReferenceDirectives(
  typeDirectiveNames: string[],
  containingFile: string,
  redirectedReference: ResolvedProjectReference | undefined,
  options: CompilerOptions
): (ResolvedTypeReferenceDirective | undefined)[] {
  /* ... */
}

const enhanceLanguageServiceHost = (host: ts.LanguageServiceHost): void => {
  host.resolveModuleNames = resolveModuleNames;
  host.resolveTypeReferenceDirectives = resolveTypeReferenceDirectives;
};