Module: index

The Nx Devkit is the underlying technology used to customize Nx to support different technologies and custom use-cases. It contains many utility functions for reading and writing files, updating configuration, working with Abstract Syntax Trees(ASTs), and more.

As with most things in Nx, the core of Nx Devkit is very simple. It only uses language primitives and immutable objects (the tree being the only exception).

Table of contents

Project Graph Enumerations

Utils Enumerations

Project Graph Classes

Utils Classes

Workspace Classes

Commands Interfaces

Other Interfaces

Project Graph Interfaces

Tree Interfaces

Utils Interfaces

Workspace Interfaces

Generators Type aliases

Other Type aliases

Package Manager Type aliases

Project Graph Type aliases

Utils Type aliases

Workspace Type aliases

Logger Variables

Utils Variables

Functions

Project Graph Enumerations

DependencyType

DependencyType: Object


Utils Enumerations

ChangeType

ChangeType: Object

Project Graph Classes

ProjectGraphBuilder

ProjectGraphBuilder: Object


Utils Classes

Hasher

Hasher: Object


Workspace Classes

Workspaces

Workspaces: Object

Commands Interfaces

Target

Target: Object


Other Interfaces

NxPlugin

NxPlugin: Object

A plugin for Nx


Project Graph Interfaces

FileData

FileData: Object


ProjectFileMap

ProjectFileMap: Object


ProjectGraph

ProjectGraph: Object


ProjectGraphDependency

ProjectGraphDependency: Object


ProjectGraphExternalNode

ProjectGraphExternalNode: Object


ProjectGraphProcessorContext

ProjectGraphProcessorContext: Object


ProjectGraphProjectNode

ProjectGraphProjectNode: Object


ProjectGraphV4

ProjectGraphV4<T>: Object

Type parameters

NameType
Tany

Tree Interfaces

FileChange

FileChange: Object


Tree

Tree: Object


Utils Interfaces

DefaultTasksRunnerOptions

DefaultTasksRunnerOptions: Object


Hash

Hash: Object


JsonParseOptions

JsonParseOptions: Object


JsonSerializeOptions

JsonSerializeOptions: Object


ModuleFederationConfig

ModuleFederationConfig: Object


RemoteCache

RemoteCache: Object


SharedLibraryConfig

SharedLibraryConfig: Object


StringDeletion

StringDeletion: Object


StringInsertion

StringInsertion: Object


Workspace Interfaces

ExecutorContext

ExecutorContext: Object


ExecutorsJson

ExecutorsJson: Object


GeneratorsJson

GeneratorsJson: Object


HasherContext

HasherContext: Object


ImplicitJsonSubsetDependency

ImplicitJsonSubsetDependency<T>: Object

Type parameters

NameType
T"*" | string[]

MigrationsJson

MigrationsJson: Object


NxAffectedConfig

NxAffectedConfig: Object


NxJsonConfiguration

NxJsonConfiguration<T>: Object

Type parameters

NameType
T"*" | string[]

ProjectConfiguration

ProjectConfiguration: Object


ProjectsConfigurations

ProjectsConfigurations: Object


TargetConfiguration

TargetConfiguration<T>: Object

Type parameters

NameType
Tany

TargetDependencyConfig

TargetDependencyConfig: Object


Task

Task: Object


TaskGraph

TaskGraph: Object


Workspace

Workspace: Object

Generators Type aliases

WorkspaceConfiguration

Ƭ WorkspaceConfiguration: Omit<ProjectsConfigurations, "projects"> & Partial<NxJsonConfiguration>


Other Type aliases

ProjectTargetConfigurator

Ƭ ProjectTargetConfigurator: (file: string) => Record<string, TargetConfiguration>

Type declaration

▸ (file): Record<string, TargetConfiguration>

Parameters
NameType
filestring
Returns

Record<string, TargetConfiguration>


Package Manager Type aliases

PackageManager

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


Project Graph Type aliases

ProjectGraphNode

Ƭ ProjectGraphNode: ProjectGraphProjectNode | ProjectGraphExternalNode


Utils Type aliases

AdditionalSharedConfig

Ƭ AdditionalSharedConfig: (string | [libraryName: string, sharedConfig: SharedLibraryConfig] | { libraryName: string ; sharedConfig: SharedLibraryConfig })[]


ModuleFederationLibrary

Ƭ ModuleFederationLibrary: Object

Type declaration

NameType
namestring
typestring

Remotes

Ƭ Remotes: string[] | [remoteName: string, remoteUrl: string][]


SharedFunction

Ƭ SharedFunction: (libraryName: string, sharedConfig: SharedLibraryConfig) => undefined | false | SharedLibraryConfig

Type declaration

▸ (libraryName, sharedConfig): undefined | false | SharedLibraryConfig

Parameters
NameType
libraryNamestring
sharedConfigSharedLibraryConfig
Returns

undefined | false | SharedLibraryConfig


SharedWorkspaceLibraryConfig

Ƭ SharedWorkspaceLibraryConfig: Object

Type declaration

NameType
getAliases() => Record<string, string>
getLibraries(eager?: boolean) => Record<string, SharedLibraryConfig>
getReplacementPlugin() => NormalModuleReplacementPlugin

StringChange

Ƭ StringChange: StringInsertion | StringDeletion


WorkspaceLibrary

Ƭ WorkspaceLibrary: Object

Type declaration

NameType
importKeystring | undefined
namestring
rootstring

WorkspaceLibrarySecondaryEntryPoint

Ƭ WorkspaceLibrarySecondaryEntryPoint: Object

Type declaration

NameType
namestring
pathstring

Workspace Type aliases

CustomHasher

Ƭ CustomHasher: (task: Task, context: HasherContext) => Promise<Hash>

Type declaration

▸ (task, context): Promise<Hash>

Parameters
NameType
taskTask
contextHasherContext
Returns

Promise<Hash>


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>


ProjectType

Ƭ ProjectType: "library" | "application"


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>>


WorkspaceJsonConfiguration

Ƭ WorkspaceJsonConfiguration: ProjectsConfigurations

Logger Variables

logger

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

Utils Variables

appRootPath

appRootPath: string = workspaceRoot


cacheDir

cacheDir: string


output

output: CLIOutput


workspaceRoot

workspaceRoot: string

Functions

addDependenciesToPackageJson

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

Add Dependencies and Dev Dependencies to package.json

For example:

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

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

Parameters

NameTypeDefault valueDescription
treeTreeundefinedTree 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, no-op otherwise


addProjectConfiguration

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

Adds project configuration to the Nx workspace.

The project configuration is stored in workspace.json or the associated project.json file. The utility will update either files.

Parameters

NameTypeDescription
treeTreethe file system tree
projectNamestringunique name. Often directories are part of the name (e.g., mydir-mylib)
projectConfigurationProjectConfigurationproject configuration
standalone?booleanshould the project use package.json? If false, the project config is inside workspace.json

Returns

void


applyAdditionalShared

applyAdditionalShared(sharedConfig, additionalShared, projectGraph): void

Add additional dependencies to the shared package that may not have been discovered by the project graph.

This can be useful for applications that use a Dependency Injection system that expects certain Singleton values to be present in the shared injection hierarchy.

Parameters

NameTypeDescription
sharedConfigRecord<string, SharedLibraryConfig>The original Shared Config
additionalSharedAdditionalSharedConfigThe additional dependencies to add
projectGraphProjectGraphThe Nx project graph

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:

const code = `bootstrap({ target: document.querySelector('#app') })`; const indexOfPropertyName = 13; // Usually determined by analyzing an AST. const updatedCode = applyChangesToString(code, [ { type: ChangeType.Insert, index: indexOfPropertyName, text: 'element', }, { type: ChangeType.Delete, start: indexOfPropertyName, length: 6, }, ]); bootstrap({ element: document.querySelector('#app'), });

Parameters

NameType
textstring
changesStringChange[]

Returns

string


applySharedFunction

applySharedFunction(sharedConfig, sharedFn): void

Apply a custom function provided by the user that will modify the Shared Config of the dependencies for the Module Federation build.

Parameters

NameTypeDescription
sharedConfigRecord<string, SharedLibraryConfig>The original Shared Config to be modified
sharedFnSharedFunctionThe custom function to run

Returns

void


convertNxExecutor

convertNxExecutor(executor): any

Convert an Nx Executor into an Angular Devkit Builder

Use this to expose a compatible Angular Builder

Parameters

NameType
executorExecutor<any>

Returns

any


convertNxGenerator

convertNxGenerator<T>(generator, skipWritingConfigInOldFormat?): (generatorOptions: T) => (tree: any, context: any) => Promise<any>

Convert an Nx Generator into an Angular Devkit Schematic.

Type parameters

NameType
Tany

Parameters

NameTypeDefault valueDescription
generatorGenerator<T>undefinedThe Nx generator to convert to an Angular Devkit Schematic.
skipWritingConfigInOldFormatbooleanfalseWhether to skip writing the configuration in the old format (the one used by the Angular DevKit).

Returns

fn

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

Parameters
NameType
generatorOptionsT
Returns

fn

▸ (tree, context): Promise<any>

Parameters
NameType
treeany
contextany
Returns

Promise<any>


createLockFile

createLockFile(packageJson, packageManager?): string

Create lock file based on the root level lock file and (pruned) package.json

Parameters

NameType
packageJsonPackageJson
packageManagerPackageManager

Returns

string


createPackageJson

createPackageJson(projectName, graph, options?): PackageJson

Creates a package.json in the output directory for support to install dependencies within containers.

If a package.json exists in the project, it will reuse that. If isProduction flag is set, it wil remove devDependencies and optional peerDependencies

Parameters

NameType
projectNamestring
graphProjectGraph
optionsObject
options.isProduction?boolean
options.root?string

Returns

PackageJson


createProjectGraphAsync

createProjectGraphAsync(opts?): Promise<ProjectGraph>

Computes and returns a ProjectGraph.

Nx will compute the graph either in a daemon process or in the current process.

Nx will compute it in the current process if:

  • The process is running in CI (CI env variable is to true or other common variables used by CI providers are set).
  • It is running in the docker container.
  • The daemon process is disabled because of the previous error when starting the daemon.
  • NX_DAEMON is set to false.
  • useDaemon is set to false in nx.json

NX_DAEMON env variable takes precedence:

  • If it is set to true, the daemon will always be used.
  • If it is set to false, the graph will always be computed in the current process.

Tip: If you want to debug project graph creation, run your command with NX_DAEMON=false.

Nx uses two layers of caching: the information about explicit dependencies stored on the disk and the information stored in the daemon process. To reset both run: nx reset.

Parameters

NameType
optsObject
opts.exitOnErrorboolean
opts.resetDaemonClient?boolean

Returns

Promise<ProjectGraph>


defaultTasksRunner

Const defaultTasksRunner(tasks, options, context?): any

Parameters

NameType
tasksTask[]
optionsDefaultTasksRunnerOptions
context?Object
context.daemon?DaemonClient
context.hasher?Hasher
context.initiatingProject?string
context.nxArgsNxArgs
context.nxJsonNxJsonConfiguration<string[] | "*">
context.projectGraphProjectGraph
context.target?string
context.taskGraph?TaskGraph

Returns

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


detectWorkspaceScope

detectWorkspaceScope(packageName): string

Detect workspace scope from the package.json name

Parameters

NameType
packageNamestring

Returns

string


ensurePackage

ensurePackage(tree, pkg, requiredVersion, options?): Promise<void>

Ensure that dependencies and devDependencies from package.json are installed at the required versions.

For example:

ensurePackage(tree, {}, { '@nrwl/jest': nxVersion });

This will check that @nrwl/jest@<nxVersion> exists in devDependencies. If it exists then function returns, otherwise it will install the package before continuing. When running with --dryRun, the function will throw when dependencies are missing.

Parameters

NameTypeDescription
treeTreethe file system tree
pkgstringthe package to check (e.g. @nrwl/jest)
requiredVersionstringthe version or semver range to check (e.g. ~1.0.0, >=1.0.0 <2.0.0)
optionsObject
options.dev?boolean-
options.throwOnMissing?boolean-

Returns

Promise<void>


extractLayoutDirectory

extractLayoutDirectory(directory): Object

Experimental

Parameters

NameType
directorystring

Returns

Object

NameType
layoutDirectorystring
projectDirectorystring

formatFiles

formatFiles(tree): Promise<void>

Formats all the created or updated files using Prettier

Parameters

NameTypeDescription
treeTreethe file system tree

Returns

Promise<void>


generateFiles

generateFiles(tree, 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:

generateFiles(tree, path.join(__dirname, 'files'), './tools/scripts', { tmpl: '', name: 'myscript', });

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
treeTreethe file system tree
srcFolderstringthe source folder of files (absolute path)
targetstringthe target folder (relative to the tree root)
substitutionsObjectan object of key-value pairs

Returns

void


getDependentPackagesForProject

getDependentPackagesForProject(projectGraph, name): Object

Parameters

NameType
projectGraphProjectGraph
namestring

Returns

Object

NameType
npmPackagesstring[]
workspaceLibrariesWorkspaceLibrary[]

getImportPath

getImportPath(npmScope, projectDirectory): string

Prefixes project name with npm scope

Parameters

NameType
npmScopestring
projectDirectorystring

Returns

string


getNpmPackageSharedConfig

getNpmPackageSharedConfig(pkgName, version): SharedLibraryConfig | undefined

Build the Module Federation Share Config for a specific package and the specified version of that package.

Parameters

NameTypeDescription
pkgNamestringName of the package to share
versionstringVersion of the package to require by other apps in the Module Federation setup

Returns

SharedLibraryConfig | undefined


getOutputsForTargetAndConfiguration

getOutputsForTargetAndConfiguration(task, node): string[]

Returns the list of outputs that will be cached.

Parameters

NameTypeDescription
taskPick<Task, "overrides" | "target">target + overrides
nodeProjectGraphProjectNodeProjectGraphProjectNode object that the task runs against

Returns

string[]


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:

execSync(`${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(tree): Map<string, ProjectConfiguration>

Get a map of all projects in a workspace.

Use readProjectConfiguration if only one project is needed.

Parameters

NameType
treeTree

Returns

Map<string, ProjectConfiguration>


getWorkspaceLayout

getWorkspaceLayout(tree): Object

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

Example:

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

Parameters

NameTypeDescription
treeTreefile system tree

Returns

Object

NameType
appsDirstring
libsDirstring
npmScopestring
standaloneAsDefaultboolean

getWorkspacePath

getWorkspacePath(tree): "/angular.json" | "/workspace.json" | null

Parameters

NameType
treeTree

Returns

"/angular.json" | "/workspace.json" | null


installPackagesTask

installPackagesTask(tree, 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
treeTreeundefinedthe file system tree
alwaysRunbooleanfalsealways run the command even if package.json hasn't changed.
cwdstring''-
packageManagerPackageManagerundefined-

Returns

void


isStandaloneProject

isStandaloneProject(tree, project): boolean

Returns if a project has a standalone configuration (project.json).

Parameters

NameTypeDescription
treeTreethe file system tree
projectstringthe project name

Returns

boolean


joinPathFragments

joinPathFragments(...fragments): string

Normalized path fragments and joins them

Parameters

NameType
...fragmentsstring[]

Returns

string


mapRemotes

mapRemotes(remotes, remoteEntryExt, determineRemoteUrl): Record<string, string>

Map remote names to a format that can be understood and used by Module Federation.

Parameters

NameTypeDescription
remotesRemotesThe remotes to map
remoteEntryExt"js" | "mjs"The file extension of the remoteEntry file
determineRemoteUrl(remote: string) => stringThe function used to lookup the URL of the served remote

Returns

Record<string, string>


mapRemotesForSSR

mapRemotesForSSR(remotes, remoteEntryExt, determineRemoteUrl): Record<string, string>

Map remote names to a format that can be understood and used by Module Federation.

Parameters

NameTypeDescription
remotesRemotesThe remotes to map
remoteEntryExt"js" | "mjs"The file extension of the remoteEntry file
determineRemoteUrl(remote: string) => stringThe function used to lookup the URL of the served remote

Returns

Record<string, string>


moveFilesToNewDirectory

moveFilesToNewDirectory(tree, oldDir, newDir): void

Analogous to cp -r oldDir newDir

Parameters

NameType
treeTree
oldDirstring
newDirstring

Returns

void


names

names(name): Object

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

Examples:

names('my-name'); // {name: 'my-name', className: 'MyName', propertyName: 'myName', constantName: 'MY_NAME', fileName: 'my-name'} names('myName'); // {name: 'myName', 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:

offsetFromRoot('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

deprecated(v17) A project graph should be passed to parseTargetString for best accuracy.

Parameters

NameType
targetStringstring

Returns

Target

parseTargetString(targetString, projectGraph): Target

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

Examples:

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

Parameters

NameTypeDescription
targetStringstringtarget reference
projectGraphProjectGraph-

Returns

Target


readAllWorkspaceConfiguration

readAllWorkspaceConfiguration(): ProjectsConfigurations & NxJsonConfiguration

TODO(vsavkin): Remove after Nx 16 is out

deprecated Use readProjectsConfigurationFromProjectGraph(await createProjectGraphAsync())

Returns

ProjectsConfigurations & NxJsonConfiguration


readCachedProjectGraph

readCachedProjectGraph(): ProjectGraph

Synchronously reads the latest cached copy of the workspace's ProjectGraph.

throws {Error} if there is no cached ProjectGraph to read from

Returns

ProjectGraph


readJson

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

Reads a json file, removes all comments and parses JSON.

Type parameters

NameType
Textends object = any

Parameters

NameTypeDescription
treeTreefile 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


readNxJson

readNxJson(tree): NxJsonConfiguration | null

Reads nx.json

Parameters

NameType
treeTree

Returns

NxJsonConfiguration | null


readProjectConfiguration

readProjectConfiguration(tree, projectName): ProjectConfiguration

Reads a project configuration.

The project configuration is stored in workspace.json or the associated project.json file. The utility will read from either file.

throws If supplied projectName cannot be found

Parameters

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

Returns

ProjectConfiguration


readRootPackageJson

readRootPackageJson(): Object

Returns

Object

NameType
dependencies?Object
devDependencies?Object

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(tree): WorkspaceConfiguration

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

This does not provide projects configuration, use readProjectConfiguration instead.

deprecated use readNxJson

Parameters

NameType
treeTree

Returns

WorkspaceConfiguration


removeDependenciesFromPackageJson

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

Remove Dependencies and Dev Dependencies from package.json

For example:

removeDependenciesFromPackageJson(tree, ['react'], ['jest']);

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

Parameters

NameTypeDefault valueDescription
treeTreeundefined-
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(tree, projectName): void

Removes the configuration of an existing project.

The project configuration is stored in workspace.json or the associated project.json file. The utility will update either file.

Parameters

NameType
treeTree
projectNamestring

Returns

void


reverse

reverse(graph): ProjectGraph

Returns a new project graph where all the edges are reversed.

For instance, if project A depends on B, in the reversed graph B will depend on A.

Parameters

NameType
graphProjectGraph

Returns

ProjectGraph


runExecutor

runExecutor<T>(targetDescription, overrides, 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:

for await (const s of await runExecutor( { project: 'myproj', target: 'serve' }, { watch: true }, context )) { // s.success }

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
overridesObject
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


sharePackages

sharePackages(packages): Record<string, SharedLibraryConfig>

Create a dictionary of packages and their Module Federation Shared Config from an array of package names.

Lookup the versions of the packages from the root package.json file in the workspace.

Parameters

NameTypeDescription
packagesstring[]Array of package names as strings

Returns

Record<string, SharedLibraryConfig>


shareWorkspaceLibraries

shareWorkspaceLibraries(libraries, tsConfigPath?): SharedWorkspaceLibraryConfig

Build an object of functions to be used with the ModuleFederationPlugin to share Nx Workspace Libraries between Hosts and Remotes.

Parameters

NameTypeDescription
librariesWorkspaceLibrary[]The Nx Workspace Libraries to share
tsConfigPathstringThe path to TS Config File that contains the Path Mappings for the Libraries

Returns

SharedWorkspaceLibraryConfig


stripIndents

stripIndents(strings, ...values): string

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

Example:

stripIndents` Options: - option1 - option2 `;

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(target): string

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

Parameters

NameTypeDescription
targetTargettarget object Examples: typescript targetToTargetString({ project: "proj", target: "test" }) // returns "proj:test" targetToTargetString({ project: "proj", target: "test", configuration: "production" }) // returns "proj:test:production"

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>(tree, path, updater, options?): void

Updates a JSON value to the file system tree

Type parameters

NameType
Textends object = any
Uextends object = T

Parameters

NameTypeDescription
treeTreeFile 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


updateNxJson

updateNxJson(tree, nxJson): void

Update nx.json

Parameters

NameType
treeTree
nxJsonNxJsonConfiguration<string[] | "*">

Returns

void


updateProjectConfiguration

updateProjectConfiguration(tree, projectName, projectConfiguration): void

Updates the configuration of an existing project.

The project configuration is stored in workspace.json or the associated project.json file. The utility will update either files.

Parameters

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

Returns

void


updateTsConfigsToJs

updateTsConfigsToJs(tree, options): void

Parameters

NameType
treeTree
optionsObject
options.projectRootstring

Returns

void


updateWorkspaceConfiguration

updateWorkspaceConfiguration(tree, 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.

deprecated use updateNxJson

Parameters

NameType
treeTree
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

NameTypeDefault value
treeTreeundefined
dirPathstringtree.root
visitor(path: string) => voidundefined

Returns

void


workspaceLayout

workspaceLayout(): Object

Returns information about where apps and libs will be created.

Returns

Object

NameType
appsDirstring
libsDirstring

writeJson

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

Writes a JSON value to the file system tree

Type parameters

NameType
Textends object = object

Parameters

NameTypeDescription
treeTreeFile 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