Module: index
Table of contents
Enumerations
Classes
Interfaces
- ExecutorContext
- FileChange
- FileData
- ImplicitJsonSubsetDependency
- JsonParseOptions
- JsonSerializeOptions
- NxAffectedConfig
- NxJsonConfiguration
- NxJsonProjectConfiguration
- NxPlugin
- ProjectConfiguration
- ProjectFileMap
- ProjectGraph
- ProjectGraphDependency
- ProjectGraphNode
- ProjectGraphProcessorContext
- StringDeletion
- StringInsertion
- Target
- TargetConfiguration
- TargetDependencyConfig
- Task
- TaskGraph
- Tree
- Workspace
- WorkspaceJsonConfiguration
Type aliases
- Executor
- Generator
- GeneratorCallback
- ImplicitDependencyEntry
- PackageManager
- ProjectType
- StringChange
- TaskGraphExecutor
- WorkspaceConfiguration
Variables
Functions
- addDependenciesToPackageJson
- addProjectConfiguration
- applyChangesToString
- convertNxExecutor
- convertNxGenerator
- detectPackageManager
- formatFiles
- generateFiles
- getPackageManagerCommand
- getPackageManagerVersion
- getProjects
- getWorkspaceLayout
- getWorkspacePath
- installPackagesTask
- joinPathFragments
- moveFilesToNewDirectory
- names
- normalizePath
- offsetFromRoot
- parseJson
- parseTargetString
- readJson
- readJsonFile
- readProjectConfiguration
- readTargetOptions
- readWorkspaceConfiguration
- removeDependenciesFromPackageJson
- removeProjectConfiguration
- runExecutor
- serializeJson
- stripIndents
- stripJsonComments
- targetToTargetString
- toJS
- updateJson
- updateProjectConfiguration
- updateTsConfigsToJs
- updateWorkspaceConfiguration
- visitNotIgnoredFiles
- writeJson
- writeJsonFile
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
Name | Default |
---|---|
T | "*" | string[] |
JsonParseOptions
• JsonParseOptions: object
JsonSerializeOptions
• JsonSerializeOptions: object
NxAffectedConfig
• NxAffectedConfig: object
NxJsonConfiguration
• NxJsonConfiguration<T>: object
Nx.json configuration
Type parameters
Name | Default |
---|---|
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
Name | Default |
---|---|
T | any |
ProjectGraphDependency
• ProjectGraphDependency: object
A dependency between two projects
ProjectGraphNode
• ProjectGraphNode<T>: object
A node describing a project in a workspace
Type parameters
Name | Default |
---|---|
T | any |
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<{ success
: boolean }> | AsyncIterableIterator<{ success
: boolean }>Implementation of a target of a project
Type parameters
Name | Default |
---|---|
T | any |
Type declaration
▸ (
options
: T, context
: ExecutorContext): Promise<{ success
: boolean }> | AsyncIterableIterator<{ success
: boolean }>Parameters
Name | Type |
---|---|
options | T |
context | ExecutorContext |
Returns: Promise<{
success
: boolean }> | AsyncIterableIterator<{ success
: boolean }>Generator
Ƭ Generator<T>: (
tree
: any, schema
: T) => void | GeneratorCallback | Promise<void | GeneratorCallback>A function that schedules updates to the filesystem to be done atomically
Type parameters
Name | Default |
---|---|
T | unknown |
Type declaration
Parameters
Name | Type |
---|---|
tree | any |
schema | T |
Returns: void | GeneratorCallback | Promise<void | GeneratorCallback>
GeneratorCallback
Ƭ GeneratorCallback: () => void | Promise<void>
A callback function that is executed after changes are made to the file system
Type declaration
▸ (): void | Promise<void>
Returns: void | Promise<void>
ImplicitDependencyEntry
Ƭ ImplicitDependencyEntry<T>: object
Type parameters
Name | Default |
---|---|
T | "*" | string[] |
Type declaration
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, { success
: boolean ; terminalOutput
: string }>>Implementation of a target of a project that handles multiple projects to be batched
Type parameters
Name | Default |
---|---|
T | any |
Type declaration
▸ (
taskGraph
: TaskGraph, options
: Record<string, T>, overrides
: T, context
: ExecutorContext): Promise<Record<string, { success
: boolean ; terminalOutput
: string }>>Parameters
Name | Type |
---|---|
taskGraph | TaskGraph |
options | Record<string, T> |
overrides | T |
context | ExecutorContext |
Returns: Promise<Record<string, {
success
: boolean ; terminalOutput
: string }>>WorkspaceConfiguration
Ƭ WorkspaceConfiguration: Omit<WorkspaceJsonConfiguration,
"projects"
> & Omit<NxJsonConfiguration, "projects"
>Variables
logger
•
Const
logger: objectType declaration
Name | Type |
---|---|
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
: Tree, dependencies
: Record<string, string>, devDependencies
: Record<string, string>, packageJsonPath?
: string): GeneratorCallbackAdd 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
Name | Type | Default value | Description |
---|---|---|---|
host | Tree | - | Tree representing file system to modify |
dependencies | Record<string, string> | - | Dependencies to be added to the dependencies section of package.json |
devDependencies | Record<string, string> | - | Dependencies to be added to the devDependencies section of package.json |
packageJsonPath | string | '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
: Tree, projectName
: string, projectConfiguration
: ProjectConfiguration & NxJsonProjectConfiguration, standalone?
: boolean): voidAdds project configuration to the Nx workspace.
The project configuration is stored in workspace.json and nx.json. The utility will update
both files.
Parameters
Name | Type | Default value | Description |
---|---|---|---|
host | Tree | - | the file system tree |
projectName | string | - | unique name. Often directories are part of the name (e.g., mydir-mylib) |
projectConfiguration | ProjectConfiguration & NxJsonProjectConfiguration | - | project configuration |
standalone | boolean | false | should the project use package.json? If false, the project config is inside workspace.json |
Returns: void
applyChangesToString
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
Name | Type |
---|---|
text | string |
changes | StringChange[] |
Returns: string
convertNxExecutor
▸ convertNxExecutor(
executor
: Executor): anyConvert an Nx Executor into an Angular Devkit Builder
Use this to expose a compatible Angular Builder
Parameters
Name | Type |
---|---|
executor | Executor |
Returns: any
convertNxGenerator
▸ convertNxGenerator<T>(
generator
: Generator<T>): functionConvert an Nx Generator into an Angular Devkit Schematic
Type parameters
Name | Default |
---|---|
T | any |
Parameters
Name | Type |
---|---|
generator | Generator<T> |
Returns: (
options
: T) => (tree
: any, context
: any) => Promise<any>detectPackageManager
▸ detectPackageManager(
dir?
: string): PackageManagerDetects which package manager is used in the workspace based on the lock file.
Parameters
Name | Type | Default value |
---|---|---|
dir | string | '' |
Returns: PackageManager
formatFiles
▸ formatFiles(
host
: Tree): Promise<void>Formats all the created or updated files using Prettier
Parameters
Name | Type | Description |
---|---|---|
host | Tree | the file system tree |
Returns: Promise<void>
generateFiles
▸ generateFiles(
host
: Tree, srcFolder
: string, target
: string, substitutions
: { [k: string]: any; }): voidGenerates 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
Name | Type | Description |
---|---|---|
host | Tree | the file system tree |
srcFolder | string | the source folder of files (absolute path) |
target | string | the target folder (relative to the host root) |
substitutions | object | an object of key-value pairs |
Returns: void
getPackageManagerCommand
▸ getPackageManagerCommand(
packageManager?
: PackageManager): PackageManagerCommandsReturns 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
Name | Type |
---|---|
packageManager | PackageManager |
Returns: PackageManagerCommands
getPackageManagerVersion
▸ getPackageManagerVersion(
packageManager?
: PackageManager): stringReturns 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
Name | Type |
---|---|
packageManager | PackageManager |
Returns: string
getProjects
Get a map of all projects in a workspace.
Use readProjectConfiguration if only one project is needed.
Parameters
Name | Type |
---|---|
host | Tree |
Returns: Map<string, ProjectConfiguration & NxJsonProjectConfiguration>
getWorkspaceLayout
▸ getWorkspaceLayout(
host
: Tree): objectReturns workspace defaults. It includes defaults folders for apps and libs,
and the default scope.
Example:
1{ appsDir: 'apps', libsDir: 'libs', npmScope: 'myorg' }
Parameters
Name | Type | Description |
---|---|---|
host | Tree | file system tree |
Returns: object
Name | Type |
---|---|
appsDir | string |
libsDir | string |
npmScope | string |
standaloneAsDefault | boolean |
getWorkspacePath
▸ getWorkspacePath(
host
: Tree): stringParameters
Name | Type |
---|---|
host | Tree |
Returns: string
installPackagesTask
▸ installPackagesTask(
host
: Tree, alwaysRun?
: boolean, cwd?
: string, packageManager?
: PackageManager): voidRuns
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
Name | Type | Default value | Description |
---|---|---|---|
host | Tree | - | the file system tree |
alwaysRun | boolean | false | always run the command even if package.json hasn't changed. |
cwd | string | '' | - |
packageManager | PackageManager | - | - |
Returns: void
joinPathFragments
▸ joinPathFragments(...
fragments
: string[]): stringNormalized path fragments and joins them
Parameters
Name | Type |
---|---|
...fragments | string[] |
Returns: string
moveFilesToNewDirectory
Parameters
Name | Type |
---|---|
host | Tree |
oldDir | string |
newDir | string |
Returns: void
names
▸ names(
name
: string): objectUtil 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
Name | Type |
---|---|
name | string |
Returns: object
Name | Type |
---|---|
className | string |
constantName | string |
fileName | string |
name | string |
propertyName | string |
normalizePath
▸ normalizePath(
osSpecificPath
: string): stringCoverts an os specific path to a unix style path
Parameters
Name | Type |
---|---|
osSpecificPath | string |
Returns: string
offsetFromRoot
▸ offsetFromRoot(
fullPathToDir
: string): stringCalculates an offset from the root of the workspace, which is useful for
constructing relative URLs.
Examples:
1offsetFromRoot('apps/mydir/myapp/'); // returns "../../../"
Parameters
Name | Type | Description |
---|---|---|
fullPathToDir | string | directory path |
Returns: string
parseJson
Parses the given JSON string and returns the object the JSON content represents.
By default javascript-style comments are allowed.
Type parameters
Name | Type | Default |
---|---|---|
T | object | any |
Parameters
Name | Type | Description |
---|---|---|
input | string | JSON content as string |
options? | JsonParseOptions | JSON parse options |
Returns: T
Object the JSON content represents
parseTargetString
▸ parseTargetString(
targetString
: string): TargetParses 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
Name | Type | Description |
---|---|---|
targetString | string | target reference |
Returns: Target
readJson
Reads a document for host, removes all comments and parses JSON.
Type parameters
Name | Type | Default |
---|---|---|
T | object | any |
Parameters
Name | Type | Description |
---|---|---|
host | Tree | file system tree |
path | string | file path |
options? | JsonParseOptions | Optional JSON Parse Options |
Returns: T
readJsonFile
▸ readJsonFile<T>(
path
: string, options?
: JsonReadOptions): TReads a JSON file and returns the object the JSON content represents.
Type parameters
Name | Type | Default |
---|---|---|
T | object | any |
Parameters
Name | Type | Description |
---|---|---|
path | string | A path to a file. |
options? | JsonReadOptions | JSON parse options |
Returns: T
Object the JSON content of the file represents
readProjectConfiguration
▸ readProjectConfiguration(
host
: Tree, projectName
: string): ProjectConfiguration & NxJsonProjectConfigurationReads 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 foundParameters
Name | Type | Description |
---|---|---|
host | Tree | the file system tree |
projectName | string | unique name. Often directories are part of the name (e.g., mydir-mylib) |
Returns: ProjectConfiguration & NxJsonProjectConfiguration
readTargetOptions
Reads and combines options for a given target.
Works as if you invoked the target yourself without passing any command lint overrides.
Type parameters
Name | Default |
---|---|
T | any |
Parameters
Name | Type |
---|---|
__namedParameters | Target |
context | ExecutorContext |
Returns: T
readWorkspaceConfiguration
Read general workspace configuration such as the default project or cli settings
This does not provide projects configuration, use readProjectConfiguration instead.
Parameters
Name | Type |
---|---|
host | Tree |
Returns: WorkspaceConfiguration
removeDependenciesFromPackageJson
▸ removeDependenciesFromPackageJson(
host
: Tree, dependencies
: string[], devDependencies
: string[], packageJsonPath?
: string): GeneratorCallbackRemove 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
Name | Type | Default value | Description |
---|---|---|---|
host | Tree | - | - |
dependencies | string[] | - | Dependencies to be removed from the dependencies section of package.json |
devDependencies | string[] | - | Dependencies to be removed from the devDependencies section of package.json |
packageJsonPath | string | 'package.json' | - |
Returns: GeneratorCallback
Callback to uninstall dependencies only if necessary. undefined is returned if changes are not necessary.
removeProjectConfiguration
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
Name | Type |
---|---|
host | Tree |
projectName | string |
Returns: void
runExecutor
▸ runExecutor<T>(
targetDescription
: { configuration?
: string ; project
: string ; target
: string }, options
: { [k: string]: any; }, context
: ExecutorContext): 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
Name | Type |
---|---|
T | object |
T.success | boolean |
Parameters
Name | Type |
---|---|
targetDescription | object |
targetDescription.configuration? | string |
targetDescription.project | string |
targetDescription.target | string |
options | object |
context | ExecutorContext |
Returns: Promise<AsyncIterableIterator<T>>
serializeJson
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
Name | Type | Default |
---|---|---|
T | object | object |
Parameters
Name | Type | Description |
---|---|---|
input | T | Object which should be serialized to JSON |
options? | JsonSerializeOptions | JSON serialize options |
Returns: string
the formatted JSON representation of the object
stripIndents
▸ stripIndents(
strings
: TemplateStringsArray, ...values
: any[]): stringRemoves indents, which is useful for printing warning and messages.
Example:
1stripIndents`
2 Options:
3 - option1
4 - option2
5`;
Parameters
Name | Type |
---|---|
strings | TemplateStringsArray |
...values | any[] |
Returns: string
stripJsonComments
▸
Const
stripJsonComments(text
: string, replaceCh?
: string): stringTakes JSON with JavaScript-style comments and remove
them. Optionally replaces every none-newline character
of comments with a replaceCharacter
Parameters
Name | Type |
---|---|
text | string |
replaceCh? | string |
Returns: string
targetToTargetString
▸ targetToTargetString(
__namedParameters
: Target): stringReturns a string in the format "project:target[:configuration]" for the target
Parameters
Name | Type |
---|---|
__namedParameters | Target |
Returns: string
toJS
▸ toJS(
tree
: Tree): voidRename and transpile any new typescript files created to javascript files
Parameters
Name | Type |
---|---|
tree | Tree |
Returns: void
updateJson
▸ updateJson<T, U>(
host
: Tree, path
: string, updater
: (value
: T) => U, options?
: JsonParseOptions & JsonSerializeOptions): voidUpdates a JSON value to the file system tree
Type parameters
Name | Type | Default |
---|---|---|
T | object | any |
U | object | T |
Parameters
Name | Type | Description |
---|---|---|
host | Tree | File system tree |
path | string | Path of JSON file in the Tree |
updater | (value : T) => U | Function that maps the current value of a JSON document to a new value to be written to the document |
options? | JsonParseOptions & JsonSerializeOptions | Optional JSON Parse and Serialize Options |
Returns: void
updateProjectConfiguration
▸ updateProjectConfiguration(
host
: Tree, projectName
: string, projectConfiguration
: ProjectConfiguration & NxJsonProjectConfiguration): voidUpdates the configuration of an existing project.
The project configuration is stored in workspace.json and nx.json. The utility will update
both files.
Parameters
Name | Type | Description |
---|---|---|
host | Tree | the file system tree |
projectName | string | unique name. Often directories are part of the name (e.g., mydir-mylib) |
projectConfiguration | ProjectConfiguration & NxJsonProjectConfiguration | project configuration |
Returns: void
updateTsConfigsToJs
Parameters
Name | Type |
---|---|
host | Tree |
options | object |
options.projectRoot | string |
Returns: void
updateWorkspaceConfiguration
Update general workspace configuration such as the default project or cli settings.
This does not update projects configuration, use updateProjectConfiguration or addProjectConfiguration instead.
Parameters
Name | Type |
---|---|
host | Tree |
workspaceConfig | WorkspaceConfiguration |
Returns: void
visitNotIgnoredFiles
Utility to act on all files in a tree that are not ignored by git.
Parameters
Name | Type |
---|---|
tree | Tree |
dirPath | string |
visitor | (path : string) => void |
Returns: void
writeJson
Writes a JSON value to the file system tree
Type parameters
Name | Type | Default |
---|---|---|
T | object | object |
Parameters
Name | Type | Description |
---|---|---|
host | Tree | File system tree |
path | string | Path of JSON file in the Tree |
value | T | Serializable value to write |
options? | JsonSerializeOptions | Optional JSON Serialize Options |
Returns: void
writeJsonFile
▸ writeJsonFile<T>(
path
: string, data
: T, options?
: JsonWriteOptions): voidSerializes the given data to JSON and writes it to a file.
Type parameters
Name | Type | Default |
---|---|---|
T | object | object |
Parameters
Name | Type | Description |
---|---|---|
path | string | A path to a file. |
data | T | data which should be serialized to JSON and written to the file |
options? | JsonWriteOptions | JSON serialize options |
Returns: void