Module: index

Table of contents

Enumerations

Classes

Interfaces

Type aliases

Variables

Functions

Enumerations

ChangeType

ChangeType: Object


DependencyType

DependencyType: Object

Type of dependency between projects

Classes

ProjectGraphBuilder

ProjectGraphBuilder: Object

Builder for adding nodes and dependencies to a ProjectGraph

Interfaces

ExecutorContext

ExecutorContext: Object

Context that is passed into an executor


FileChange

FileChange: Object

Description of a file change in the Nx virtual file system/


FileData

FileData: Object

Some metadata about a file


ImplicitJsonSubsetDependency

ImplicitJsonSubsetDependency<T>: Object

Type parameters

NameType
T"*" | string[]

JsonParseOptions

JsonParseOptions: Object


JsonSerializeOptions

JsonSerializeOptions: Object


NxAffectedConfig

NxAffectedConfig: Object


NxJsonConfiguration

NxJsonConfiguration<T>: Object

Nx.json configuration

Type parameters

NameType
T"*" | string[]

NxJsonProjectConfiguration

NxJsonProjectConfiguration: Object


NxPlugin

NxPlugin: Object

A plugin for Nx


ProjectConfiguration

ProjectConfiguration: Object

Project configuration


ProjectFileMap

ProjectFileMap: Object

A list of files separated by the project they belong to


ProjectGraph

ProjectGraph<T>: Object

A Graph of projects in the workspace and dependencies between them

Type parameters

NameType
Tany

ProjectGraphDependency

ProjectGraphDependency: Object

A dependency between two projects


ProjectGraphNode

ProjectGraphNode<T>: Object

A node describing a project in a workspace

Type parameters

NameType
Tany

ProjectGraphProcessorContext

ProjectGraphProcessorContext: Object

Additional information to be used to process a project graph


StringDeletion

StringDeletion: Object


StringInsertion

StringInsertion: Object


Target

Target: Object


TargetConfiguration

TargetConfiguration: Object

Target's configuration


TargetDependencyConfig

TargetDependencyConfig: Object


Task

Task: Object

A representation of the invocation of an Executor


TaskGraph

TaskGraph: Object

Graph of Tasks to be executed


Tree

Tree: Object

Virtual file system tree.


Workspace

Workspace: Object


WorkspaceJsonConfiguration

WorkspaceJsonConfiguration: Object

Workspace configuration

Type aliases

Executor

Ƭ Executor<T>: (options: T, context: ExecutorContext) => Promise<Object> | AsyncIterableIterator<Object>

Type parameters

NameType
Tany

Type declaration

▸ (options, context): Promise<Object> | AsyncIterableIterator<Object>

Implementation of a target of a project

Parameters
NameType
optionsT
contextExecutorContext
Returns

Promise<Object> | AsyncIterableIterator<Object>


Generator

Ƭ Generator<T>: (tree: any, schema: T) => void | GeneratorCallback | Promise<void | GeneratorCallback>

Type parameters

NameType
Tunknown

Type declaration

▸ (tree, schema): void | GeneratorCallback | Promise<void | GeneratorCallback>

A function that schedules updates to the filesystem to be done atomically

Parameters
NameType
treeany
schemaT
Returns

void | GeneratorCallback | Promise<void | GeneratorCallback>


GeneratorCallback

Ƭ GeneratorCallback: () => void | Promise<void>

Type declaration

▸ (): void | Promise<void>

A callback function that is executed after changes are made to the file system

Returns

void | Promise<void>


ImplicitDependencyEntry

Ƭ ImplicitDependencyEntry<T>: Object

Type parameters

NameType
T"*" | string[]

Index signature

▪ [key: string]: T | ImplicitJsonSubsetDependency<T>


PackageManager

Ƭ PackageManager: "yarn" | "pnpm" | "npm"


ProjectType

Ƭ ProjectType: "library" | "application"

Type of project supported


StringChange

Ƭ StringChange: StringInsertion | StringDeletion

A change to be made to a string


TaskGraphExecutor

Ƭ TaskGraphExecutor<T>: (taskGraph: TaskGraph, options: Record<string, T>, overrides: T, context: ExecutorContext) => Promise<Record<string, Object>>

Type parameters

NameType
Tany

Type declaration

▸ (taskGraph, options, overrides, context): Promise<Record<string, Object>>

Implementation of a target of a project that handles multiple projects to be batched

Parameters
NameType
taskGraphTaskGraph
optionsRecord<string, T>
overridesT
contextExecutorContext
Returns

Promise<Record<string, Object>>


WorkspaceConfiguration

Ƭ WorkspaceConfiguration: Omit<WorkspaceJsonConfiguration, "projects"> & Omit<NxJsonConfiguration, "projects">

Variables

logger

Const logger: Object

Type declaration

NameType
debug(...s: any[]) => void
error(s: any) => void
fatal(...s: any[]) => void
info(s: any) => void
log(...s: any[]) => void
warn(s: any) => void

Functions

addDependenciesToPackageJson

addDependenciesToPackageJson(host, dependencies, devDependencies, packageJsonPath?): GeneratorCallback

Add Dependencies and Dev Dependencies to package.json

For example:

1addDependenciesToPackageJson(host, { react: 'latest' }, { jest: 'latest' });

This will add react and jest to the dependencies and devDependencies sections of package.json respectively.

Parameters

NameTypeDefault valueDescription
hostTreeundefinedTree representing file system to modify
dependenciesRecord<string, string>undefinedDependencies to be added to the dependencies section of package.json
devDependenciesRecord<string, string>undefinedDependencies to be added to the devDependencies section of package.json
packageJsonPathstring'package.json'Path to package.json

Returns

GeneratorCallback

Callback to install dependencies only if necessary. undefined is returned if changes are not necessary.


addProjectConfiguration

addProjectConfiguration(host, projectName, projectConfiguration, standalone?): void

Adds project configuration to the Nx workspace.

The project configuration is stored in workspace.json and nx.json. The utility will update both files.

Parameters

NameTypeDefault valueDescription
hostTreeundefinedthe file system tree
projectNamestringundefinedunique name. Often directories are part of the name (e.g., mydir-mylib)
projectConfigurationProjectConfiguration & NxJsonProjectConfigurationundefinedproject configuration
standalonebooleanfalseshould the project use package.json? If false, the project config is inside workspace.json

Returns

void


applyChangesToString

applyChangesToString(text, changes): string

Applies a list of changes to a string's original value.

This is useful when working with ASTs.

For Example, to rename a property in a method's options:

1const code = `bootstrap({
2  target: document.querySelector('#app')
3})`;
4
5const indexOfPropertyName = 13; // Usually determined by analyzing an AST.
6const updatedCode = applyChangesToString(code, [
7  {
8    type: ChangeType.Insert,
9    index: indexOfPropertyName,
10    text: 'element',
11  },
12  {
13    type: ChangeType.Delete,
14    start: indexOfPropertyName,
15    length: 6,
16  },
17]);
18
19bootstrap({
20  element: document.querySelector('#app'),
21});

Parameters

NameType
textstring
changesStringChange[]

Returns

string


convertNxExecutor

convertNxExecutor(executor): any

Convert an Nx Executor into an Angular Devkit Builder

Use this to expose a compatible Angular Builder

Parameters

NameType
executorExecutor

Returns

any


convertNxGenerator

convertNxGenerator<T>(generator): (options: T) => (tree: any, context: any) => Promise<any>

Convert an Nx Generator into an Angular Devkit Schematic

Type parameters

NameType
Tany

Parameters

NameType
generatorGenerator<T>

Returns

fn

▸ (options): (tree: any, context: any) => Promise<any>

Parameters
NameType
optionsT
Returns

fn

▸ (tree, context): Promise<any>

Parameters
NameType
treeany
contextany
Returns

Promise<any>


detectPackageManager

detectPackageManager(dir?): PackageManager

Detects which package manager is used in the workspace based on the lock file.

Parameters

NameTypeDefault value
dirstring''

Returns

PackageManager


formatFiles

formatFiles(host): Promise<void>

Formats all the created or updated files using Prettier

Parameters

NameTypeDescription
hostTreethe file system tree

Returns

Promise<void>


generateFiles

generateFiles(host, srcFolder, target, substitutions): void

Generates a folder of files based on provided templates.

While doing so it performs two substitutions:

  • Substitutes segments of file names surrounded by __
  • Uses ejs to substitute values in templates

Examples:

1generateFiles(host, path.join(__dirname, 'files'), './tools/scripts', {
2  tmpl: '',
3  name: 'myscript',
4});

This command will take all the files from the files directory next to the place where the command is invoked from. It will replace all __tmpl__ with '' and all __name__ with 'myscript' in the file names, and will replace all <%= name %> with myscript in the files themselves. tmpl: '' is a common pattern. With it you can name files like this: index.ts__tmpl__, so your editor doesn't get confused about incorrect TypeScript files.

Parameters

NameTypeDescription
hostTreethe file system tree
srcFolderstringthe source folder of files (absolute path)
targetstringthe target folder (relative to the host root)
substitutionsObjectan object of key-value pairs

Returns

void


getPackageManagerCommand

getPackageManagerCommand(packageManager?): PackageManagerCommands

Returns commands for the package manager used in the workspace. By default, the package manager is derived based on the lock file, but it can also be passed in explicitly.

Example:

1execSync(`${getPackageManagerCommand().addDev} my-dev-package`);

Parameters

NameType
packageManagerPackageManager

Returns

PackageManagerCommands


getPackageManagerVersion

getPackageManagerVersion(packageManager?): string

Returns the version of the package manager used in the workspace. By default, the package manager is derived based on the lock file, but it can also be passed in explicitly.

Parameters

NameType
packageManagerPackageManager

Returns

string


getProjects

getProjects(host): Map<string, ProjectConfiguration & NxJsonProjectConfiguration>

Get a map of all projects in a workspace.

Use readProjectConfiguration if only one project is needed.

Parameters

NameType
hostTree

Returns

Map<string, ProjectConfiguration & NxJsonProjectConfiguration>


getWorkspaceLayout

getWorkspaceLayout(host): Object

Returns workspace defaults. It includes defaults folders for apps and libs, and the default scope.

Example:

1{ appsDir: 'apps', libsDir: 'libs', npmScope: 'myorg' }

Parameters

NameTypeDescription
hostTreefile system tree

Returns

Object

NameType
appsDirstring
libsDirstring
npmScopestring
standaloneAsDefaultboolean

getWorkspacePath

getWorkspacePath(host): string

Parameters

NameType
hostTree

Returns

string


installPackagesTask

installPackagesTask(host, alwaysRun?, cwd?, packageManager?): void

Runs npm install or yarn install. It will skip running the install if package.json hasn't changed at all or it hasn't changed since the last invocation.

Parameters

NameTypeDefault valueDescription
hostTreeundefinedthe file system tree
alwaysRunbooleanfalsealways run the command even if package.json hasn't changed.
cwdstring''-
packageManagerPackageManagerundefined-

Returns

void


joinPathFragments

joinPathFragments(...fragments): string

Normalized path fragments and joins them

Parameters

NameType
...fragmentsstring[]

Returns

string


moveFilesToNewDirectory

moveFilesToNewDirectory(host, oldDir, newDir): void

Parameters

NameType
hostTree
oldDirstring
newDirstring

Returns

void


names

names(name): Object

Util function to generate different strings based off the provided name.

Examples:

1names('my-name'); // {name: 'my-name', className: 'MyName', propertyName: 'myName', constantName: 'MY_NAME', fileName: 'my-name'}
2names('myName'); // {name: 'my-name', className: 'MyName', propertyName: 'myName', constantName: 'MY_NAME', fileName: 'my-name'}

Parameters

NameType
namestring

Returns

Object

NameType
classNamestring
constantNamestring
fileNamestring
namestring
propertyNamestring

normalizePath

normalizePath(osSpecificPath): string

Coverts an os specific path to a unix style path

Parameters

NameType
osSpecificPathstring

Returns

string


offsetFromRoot

offsetFromRoot(fullPathToDir): string

Calculates an offset from the root of the workspace, which is useful for constructing relative URLs.

Examples:

1offsetFromRoot('apps/mydir/myapp/'); // returns "../../../"

Parameters

NameTypeDescription
fullPathToDirstringdirectory path

Returns

string


parseJson

parseJson<T>(input, options?): T

Parses the given JSON string and returns the object the JSON content represents. By default javascript-style comments are allowed.

Type parameters

NameType
Textends object``any

Parameters

NameTypeDescription
inputstringJSON content as string
options?JsonParseOptionsJSON parse options

Returns

T

Object the JSON content represents


parseTargetString

parseTargetString(targetString): Target

Parses a target string into {project, target, configuration}

Examples:

1parseTargetString('proj:test'); // returns { project: "proj", target: "test" }
2parseTargetString('proj:test:production'); // returns { project: "proj", target: "test", configuration: "production" }

Parameters

NameTypeDescription
targetStringstringtarget reference

Returns

Target


readJson

readJson<T>(host, path, options?): T

Reads a document for host, removes all comments and parses JSON.

Type parameters

NameType
Textends object``any

Parameters

NameTypeDescription
hostTreefile system tree
pathstringfile path
options?JsonParseOptionsOptional JSON Parse Options

Returns

T


readJsonFile

readJsonFile<T>(path, options?): T

Reads a JSON file and returns the object the JSON content represents.

Type parameters

NameType
Textends object``any

Parameters

NameTypeDescription
pathstringA path to a file.
options?JsonReadOptionsJSON parse options

Returns

T

Object the JSON content of the file represents


readProjectConfiguration

readProjectConfiguration(host, projectName): ProjectConfiguration & NxJsonProjectConfiguration

Reads a project configuration.

The project configuration is stored in workspace.json and nx.json. The utility will read both files.

throws If supplied projectName cannot be found

Parameters

NameTypeDescription
hostTreethe file system tree
projectNamestringunique name. Often directories are part of the name (e.g., mydir-mylib)

Returns

ProjectConfiguration & NxJsonProjectConfiguration


readTargetOptions

readTargetOptions<T>(__namedParameters, context): T

Reads and combines options for a given target.

Works as if you invoked the target yourself without passing any command lint overrides.

Type parameters

NameType
Tany

Parameters

NameType
__namedParametersTarget
contextExecutorContext

Returns

T


readWorkspaceConfiguration

readWorkspaceConfiguration(host): WorkspaceConfiguration

Read general workspace configuration such as the default project or cli settings

This does not provide projects configuration, use readProjectConfiguration instead.

Parameters

NameType
hostTree

Returns

WorkspaceConfiguration


removeDependenciesFromPackageJson

removeDependenciesFromPackageJson(host, dependencies, devDependencies, packageJsonPath?): GeneratorCallback

Remove Dependencies and Dev Dependencies from package.json

For example:

1removeDependenciesFromPackageJson(host, ['react'], ['jest']);

This will remove react and jest from the dependencies and devDependencies sections of package.json respectively.

Parameters

NameTypeDefault valueDescription
hostTreeundefined-
dependenciesstring[]undefinedDependencies to be removed from the dependencies section of package.json
devDependenciesstring[]undefinedDependencies to be removed from the devDependencies section of package.json
packageJsonPathstring'package.json'-

Returns

GeneratorCallback

Callback to uninstall dependencies only if necessary. undefined is returned if changes are not necessary.


removeProjectConfiguration

removeProjectConfiguration(host, projectName): void

Removes the configuration of an existing project.

The project configuration is stored in workspace.json and nx.json. The utility will update both files.

Parameters

NameType
hostTree
projectNamestring

Returns

void


runExecutor

runExecutor<T>(targetDescription, options, context): Promise<AsyncIterableIterator<T>>

Loads and invokes executor.

This is analogous to invoking executor from the terminal, with the exception that the params aren't parsed from the string, but instead provided parsed already.

Apart from that, it works the same way:

  • it will load the workspace configuration
  • it will resolve the target
  • it will load the executor and the schema
  • it will load the options for the appropriate configuration
  • it will run the validations and will set the default
  • and, of course, it will invoke the executor

Example:

1for await (const s of await runExecutor(
2  { project: 'myproj', target: 'serve' },
3  { watch: true },
4  context
5)) {
6  // s.success
7}

Note that the return value is a promise of an iterator, so you need to await before iterating over it.

Type parameters

NameType
Textends Object

Parameters

NameType
targetDescriptionObject
targetDescription.configuration?string
targetDescription.projectstring
targetDescription.targetstring
optionsObject
contextExecutorContext

Returns

Promise<AsyncIterableIterator<T>>


serializeJson

serializeJson<T>(input, options?): string

Serializes the given data to a JSON string. By default the JSON string is formatted with a 2 space intendation to be easy readable.

Type parameters

NameType
Textends object``object

Parameters

NameTypeDescription
inputTObject which should be serialized to JSON
options?JsonSerializeOptionsJSON serialize options

Returns

string

the formatted JSON representation of the object


stripIndents

stripIndents(strings, ...values): string

Removes indents, which is useful for printing warning and messages.

Example:

1stripIndents`
2 Options:
3 - option1
4 - option2
5`;

Parameters

NameType
stringsTemplateStringsArray
...valuesany[]

Returns

string


stripJsonComments

Const stripJsonComments(text, replaceCh?): string

Takes JSON with JavaScript-style comments and remove them. Optionally replaces every none-newline character of comments with a replaceCharacter

Parameters

NameType
textstring
replaceCh?string

Returns

string


targetToTargetString

targetToTargetString(__namedParameters): string

Returns a string in the format "project:target[:configuration]" for the target

Parameters

NameType
__namedParametersTarget

Returns

string


toJS

toJS(tree): void

Rename and transpile any new typescript files created to javascript files

Parameters

NameType
treeTree

Returns

void


updateJson

updateJson<T, U>(host, path, updater, options?): void

Updates a JSON value to the file system tree

Type parameters

NameType
Textends object``any
Uextends object``T

Parameters

NameTypeDescription
hostTreeFile system tree
pathstringPath of JSON file in the Tree
updater(value: T) => UFunction that maps the current value of a JSON document to a new value to be written to the document
options?JsonParseOptions & JsonSerializeOptionsOptional JSON Parse and Serialize Options

Returns

void


updateProjectConfiguration

updateProjectConfiguration(host, projectName, projectConfiguration): void

Updates the configuration of an existing project.

The project configuration is stored in workspace.json and nx.json. The utility will update both files.

Parameters

NameTypeDescription
hostTreethe file system tree
projectNamestringunique name. Often directories are part of the name (e.g., mydir-mylib)
projectConfigurationProjectConfiguration & NxJsonProjectConfigurationproject configuration

Returns

void


updateTsConfigsToJs

updateTsConfigsToJs(host, options): void

Parameters

NameType
hostTree
optionsObject
options.projectRootstring

Returns

void


updateWorkspaceConfiguration

updateWorkspaceConfiguration(host, workspaceConfig): void

Update general workspace configuration such as the default project or cli settings.

This does not update projects configuration, use updateProjectConfiguration or addProjectConfiguration instead.

Parameters

NameType
hostTree
workspaceConfigWorkspaceConfiguration

Returns

void


visitNotIgnoredFiles

visitNotIgnoredFiles(tree, dirPath?, visitor): void

Utility to act on all files in a tree that are not ignored by git.

Parameters

NameType
treeTree
dirPathstring
visitor(path: string) => void

Returns

void


writeJson

writeJson<T>(host, path, value, options?): void

Writes a JSON value to the file system tree

Type parameters

NameType
Textends object``object

Parameters

NameTypeDescription
hostTreeFile system tree
pathstringPath of JSON file in the Tree
valueTSerializable value to write
options?JsonSerializeOptionsOptional JSON Serialize Options

Returns

void


writeJsonFile

writeJsonFile<T>(path, data, options?): void

Serializes the given data to JSON and writes it to a file.

Type parameters

NameType
Textends object``object

Parameters

NameTypeDescription
pathstringA path to a file.
dataTdata which should be serialized to JSON and written to the file
options?JsonWriteOptionsJSON serialize options

Returns

void