@zenflux/cli
@zenflux/cli
Overview
The repository contains a CLI tool called @z-cli that offers functionalities related to building, publishing, watching monorepo workspaces, and generating projects from templates.
It utilizes technologies like Babel, Rollup, TypeScript, SWC and Verdaccio.
The tool is designed to simplify the development process by providing a command-line interface with various commands for managing and building projects. It includes modules for handling npm registry operations.
The tool's value proposition lies in its ability to automate repetitive tasks and streamline project workflows, ultimately enhancing developer productivity.
Installation
Via package manager, bun install @zenflux/cli
Features
The CLI provides several commands, each starting with the @ symbol.
These commands are designed to help you manage and build your projects efficiently.
Building Projects
- The CLI tool provides a command for building projects.
- It utilizes technologies such as
SWC,Rollup,ApiExtractor, and more to bundle and transpile code for distribution. - Developers can use this feature to create distribution-ready packages.
- When workspace has multiple packages, the tool can build all packages or a specific package, with support of multiple formats and extension.
- It can also generate declaration files and handle external dependencies.
- Utilizing multithreading, the tool can build multiple packages simultaneously, improving performance.
CLI Commands:
@build@watch@typecheckDefault Behavior ( without arguments ):
@z-cli @build@z-cli @watch@z-cli @typecheck- Current working directory is workspace: Builds all packages in the workspace
- Current working directory is package: Build the current package
CLI Options
--config:
- Description: Specify a custom config file
- Examples:
--config <config-file-name>--config zenflux.test.config.ts
--workspace:
- Description: Run for a specific workspace
- Examples:
--workspace <company@package-name>--workspace <package-name>--workspace <package-name-a>, <package-name-b>--workspace "prefix-*", "react-*"
--dev:
- Description: Run in development mode
- Behaviors:
- Shows all api-exporter diagnostics
- No minification
- Loads a different tsconfig file:
tsconfig.{format}.dev.jsonortsconfig.dev.json - Sets
process.env.NODE_ENVtodevelopment
--haltOnDiagnosticError:
- Description: Halt on typescript diagnostic error
- Behaviors:
- Kill the process if typescript diagnostic error occurred
- Kill the process if typescript diagnostic error occurred
--no-diagnostic:
- Description: Disable typescript diagnostics
- Behaviors:
- No typescript diagnostics
- No typescript diagnostics
--no-declaration:
- Description: Disable declaration file generation
- Behaviors:
- No declaration file generation
- No api-exporter will be used
Configuration file (
zenflux.config.ts);format:- Array of formats to build, eg:
[ "es", "cjs", "umd" ]
- Array of formats to build, eg:
extensions:- Array of extensions to build, eg:
[ ".ts", ".js" ]
- Array of extensions to build, eg:
inputPath:- Path to the input file
outputName:- Name of the output package
outputFileName:- Name of the output file
inputDtsPath(optional):- Path to the input dts file
outputDtsPath(optional):- Path to the output dts file
globals(optional):- Object that will be used as globals, eg:
{ jquery: "jQuery" }
- Object that will be used as globals, eg:
external(optional):- Array of external packages, packages that should not be bundled, eg:
react-dom
- Array of external packages, packages that should not be bundled, eg:
enableCustomLoader(optional):- Enables zCustomLoader, (moduleForwarding depended on this)
enableCjsAsyncWrap(optional):- Enables cjs top level async wrap
moduleForwardingThis property is an object that maps module names to their respective paths. It is used to redirect module imports to different locations, which can be particularly useful in a monorepo setup.
The keys of the object represent the module names that you want to redirect. The values are another object that maps the source module path to the target module path.For example:
moduleForwarding: { "@zenflux/react-reconciler": { "@zenflux/react-scheduler": "@zenflux/react-scheduler/mock", }, "@zenflux/react-noop-renderer": { "@zenflux/react-scheduler": "@zenflux/react-scheduler/mock", } }In the above example, whenever the
@zenflux/react-reconcilermodule imports@zenflux/react-scheduler, it will be redirected to@zenflux/react-scheduler/mock.
The same goes for@zenflux/react-noop-renderer.
This allows you to substitute certain modules with others, which can be especially useful for testing or development purposes.
Single Configuration
import type { IZConfig } from "@zenflux/cli"; const config: IZConfig = { format: [ "es", "cjs" ], extensions: [ ".ts" ], inputPath: "src/index.ts", outputName: "@my-mono-repo/demo-package", outputFileName: "zenflux-core", inputDtsPath: "dist/src/index.d.ts", outputDtsPath: "dist/demo-package.d.ts", globals: { jquery: "jQuery", }, external: [ "react-dom", ], }; export default config;
- Multi Configuration
Each key in the configs object represents a package in your workspace. The key should match the name of the package. The$defaultskey is optional and can be used to define default configurations that apply to all packages. These defaults can be overridden by package-specific configurations. Each package-specific configuration is an object that follows theIZConfigInMultiinterface. This includes properties like: inputPathoutputFileNameformatextensions- This format allows you to manage configurations for multiple packages in a centralized manner, making it easier to maintain and update configurations as your workspace grows.
- Example
import type { IZConfigs } from "@zenflux/cli"; const configs: IZConfigs = { $defaults: { format: [ "es", "cjs" ], extensions: [ ".ts" ], }, "@zenflux/react-scheduler": { inputPath: "src/index.ts", outputFileName: "zenflux-react-scheduler", inputDtsPath: "dist/src/index.d.ts", outputDtsPath: "dist/zenflux-react-scheduler.d.ts", }, "@zenflux/react-scheduler/mock": { inputPath: "src/index.mock.ts", outputFileName: "zenflux-react-scheduler.mock", inputDtsPath: "dist/src/index.mock.d.ts", outputDtsPath: "dist/zenflux-react-scheduler.mock.d.ts", } }; export default configs;
- Example
- Typescript configuration -
tsconfig.json- Fallback flow:
--devtsconfig.{format}.dev.jsontsconfig.dev.json
- Regular
tsconfig.{format}.jsontsconfig.json
- Fallback flow:
Flow
- Initialization: The run method begins by retrieving the configurations using the
getConfigsmethod and the configuration paths using thegetConfigsPathsmethod.- Configuration Retrieval: It loads the
zenflux.config.tsfor each package and creates aTZBuildOptionsobject. It assigns the index of the current configuration to the thread property of theTZBuildOptionsobject if the number of configurations is greater thanDEFAULT_MIN_SINGLE_BUILD_CONFIGS. - Configuration Loop: For each configuration path, it reads the TypeScript configuration using the
zTSConfigReadmethod, performs pre-diagnostics using thezTSPreDiagnosticsmethod, and loads the relevanttsconfig.{format}.json. - Package Build: For each package format, it builds the package and fires the
onBuiltFormatcallback if provided inzenflux.config.ts. - Post-Build: After building all configurations, for each configuration path, it begins the creation of declaration files and creates them using the
zTSCreateDeclarationmethod. - Declaration File Consolidation: It then merges all the declaration files into a single declaration file per package using the
zApiExportermethod, ifinputDtsPathandoutputDtsPathare provided inzenflux.config.ts. - Api-Extractor: The
zApiExportermethod bundles multiple declaration files into a single declaration file. This operation eases usage for the package consumers. If operating in development mode, it also generates a diagnostics log for each package with paths like:${ projectPath }/log/api-extractor-diagnostics.${ buildOutputFileName }.log - @watch
- Initialization: The
@watchcommand starts by retrieving the configurations for each package in your workspace. These configurations are defined in thezenflux.config.tsfile of each package. - Watcher Creation: It sets up a file watcher using the
chokidar.watchmethod. This watcher monitors the files in your workspace for any changes. - Configuration Loop: For each package configuration, it creates a separate build process. This means that each package in your workspace has its own independent build process that runs whenever a file in that package changes.
- Rollup Configuration: For each package, it creates a Rollup configuration. This configuration defines how the package should be bundled.
- Watcher Setup: It sets up a watcher for each package. When the watcher detects a change in a package, it triggers the build process for that package. To avoid triggering multiple builds for rapid successive changes, the build process is debounced using the
debouncefunction. - Change Detection: Whenever a file in a package changes, the watcher triggers the build process for that package. The build process is triggered after a delay to ensure that multiple rapid changes do not trigger multiple builds.
- Post-Build: After each build process, it performs TypeScript pre-diagnostics for all configurations. This helps to catch and report any TypeScript errors that might have been introduced during the changes.
- Watch Method: The
watchmethod is used to set up a watcher for a specific package. It triggers a build process whenever a change is detected in the package. The build process is debounced to avoid triggering multiple builds for rapid successive changes. - Debounce Function: The
debouncefunction ensures that the build process is not triggered more than once within a specified delay.
This is useful to avoid triggering multiple builds for rapid successive changes.
The debounce function works by delaying the execution of the build process until a certain amount of time has passed without any new changes being detected. This ensures that if multiple changes are made in quick succession, the build process will only be triggered once, after the last change.
- Initialization: The
- Configuration Retrieval: It loads the
Type Checking Projects
The CLI tool provides a command for performing TypeScript type checking across workspace packages without building or generating declarations.
- The
@typecheckcommand runs TypeScript's type checking on your code to catch type errors early in development. - It supports checking all packages in a workspace or specific packages using workspace filtering.
- For single packages, it runs type checking synchronously for faster feedback.
- For multiple packages, it utilizes parallel execution to check packages simultaneously, improving performance.
- The command uses the main
tsconfig.jsonfile in each package (not format-specific configs).
CLI Commands:
@typecheckDefault Behavior:
@z-cli @typecheck- Current working directory is workspace: Typechecks all packages in the workspace
- Current working directory is package: Typecheck the current package
CLI Options
--workspace:
- Description: Run for a specific workspace
- Examples:
--workspace <company@package-name>--workspace <package-name>--workspace <package-name-a>, <package-name-b>--workspace "prefix-*", "react-*"
--haltOnDiagnosticError:
- Description: Halt on typescript diagnostic error
- Behaviors:
- Kill the process if typescript diagnostic error occurred
- Kill the process if typescript diagnostic error occurred
--config:
- Description: Specify a custom config file
- Examples:
--config <config-file-name>--config zenflux.test.config.ts
Examples
@z-cli @typecheck- Typecheck all packages in workspace@z-cli @typecheck --workspace "react-*"- Typecheck packages matching pattern@z-cli @typecheck --workspace zenflux-cli- Typecheck specific package@z-cli @typecheck --haltOnDiagnosticError- Stop on first type error
Publishing Packages
The tool supports publishing npm packages to a registry. It includes features for configuring and publishing packages, ensuring they are available for installation by other developers. Developers can manage and publish their packages with ease.
CLI Commands:
@publishDefault Behavior:
@z-cli @publish- Trying to publish all publishable packages in the workspace (select able by console menu)
CLI Options
- [package-name]:
- Description: Specify package(s) to publish directly, skipping interactive selection
- Examples:
@z-cli @publish @zenflux/core@z-cli @publish @zenflux/core,@zenflux/cli
- --token:
- Description: Specify an npm authentication token for publishing
- Examples:
--token=npm_xxxxxxxxxxxx--token npm_xxxxxxxxxxxx
- Note: Token can also be set via
NPM_TOKENenvironment variable or.npmrcfile - Priority:
--tokenflag >NPM_TOKENenv >.npmrcfile
- [package-name]:
Flow:
- Determining if local npm will be used
- Determining if the package is publishable
- Asking the user for packages to publish
- Replacing workspace: dependency ranges with concrete semver versions
- Uses the just-bumped local version when the dependency is part of the current publish batch
- Falls back to the latest version from the npm registry if no local version is available
- Showing the user the packages/files that will be published
- Asking the user for confirmation, and publishing the packages
Generating Projects from Templates
The tool supports generating new projects from predefined templates stored in the templates/ directory.
CLI Commands:
@generateDefault Behavior:
@z-cli @generate- Lists all available templates from
templates/* - Prompts for template variable values (defined in
zenflux.template-vars.txt) - Lets user select target workspace from
package.jsonworkspaces - Prompts for project name
- Copies template files with variable replacement to selected workspace
- Lists all available templates from
Template Variable Format (
zenflux.template-vars.txt):${@zenflux/project-name}$,eg: @zenflux/react-commander ${project-name}$,eg: react-commander $server_port_number$,eg 8080- Format:
${variable-name}$,eg: example-value - Variables are replaced throughout all template files during generation
- Format:
Examples:
@z-cli @generate- Start interactive template generation
Registry Operations
The tool handles interactions with npm registries, creating a local npm registry for testing and development purposes
CLI Commands:
@registrySub Commands:
- @server:
- Description: Starts a local npm registry server.
- Usage:
@z-cli @registry @server
- @use:
- Description: Use npm with custom configuration, which will be forwarded to the local npm server.
- Arguments:
id: Id of the npm registry server, can be obtained using:@registry @listcommandcommand: A npm command to execute against the registry
- Examples:
@z-cli @registry @use npm <id> <command>@z-cli @registry @use npm 4a1a whoami@z-cli @registry @use npm 4a1a install
- @list:
- Description: List all online npm registry servers.
- Usage:
@z-cli @registry @list
- @clean:
- Description: Delete current npm registry server and '.npmrc' token.
- Usage:
@z-cli @registry @clean
- @server:
Global arguments
--zvm-verbose: Log tsnode-vm verbose, shows modules resolution
--verbose: Log verbose
--help: Show help
Screenshots
@z-cli @build --workspace "react-*" --no-diagnostic --no-declaration
Building all React packages without diagnostics and declaration files.
@z-cli @watch --workspace "react-*" --no-diagnostic --no-declaration
Watching all React packages without diagnostics and declaration files.
@z-cli @watch --workspace "react-*" --verbose
Verbose mode for watching all React packages.