The JS plugin for Nx contains executors and generators that provide the best experience for developing JavaScript and TypeScript projects.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
@nx/js provides comprehensive package.json management utilities for creating, updating, and maintaining package manifests with support for exports fields, entry points, dependency management, and build artifact integration.
Creates package.json files with dependency resolution, exports field generation, and Nx-specific optimizations.
/**
* Creates package.json for a project with dependency resolution
* @param projectName - Name of the project
* @param graph - Project dependency graph
* @param options - Package.json creation options
* @returns Generated package.json object
*/
function createPackageJson(
projectName: string,
graph: ProjectGraph,
options: CreatePackageJsonOptions
): PackageJson;
interface CreatePackageJsonOptions {
target?: string; // Target name for the build
root?: string; // Workspace root directory
isProduction?: boolean; // Include only production dependencies
helperDependencies?: string[]; // Additional helper dependencies to include
}Usage Example:
import { createPackageJson } from "@nx/js";
const packageJson = createPackageJson('my-lib', projectGraph, {
target: 'build',
isProduction: true,
helperDependencies: ['tslib']
});Updates existing package.json files with build artifacts, exports fields, and dependency information.
/**
* Updates package.json with build artifacts and dependency information
* @param options - Update configuration options
* @param context - Nx executor context
* @param target - Target project node
* @param dependencies - Array of dependent buildable project nodes
* @param fileMap - Optional project file map for additional context
*/
function updatePackageJson(
options: UpdatePackageJsonOption,
context: ExecutorContext,
target: ProjectGraphProjectNode,
dependencies: DependentBuildableProjectNode[],
fileMap?: ProjectFileMap
): void;
/**
* Gets updated package.json content without writing to file system
* @param packageJson - Original package.json object
* @param options - Update configuration options
* @returns Updated package.json object
*/
function getUpdatedPackageJsonContent(
packageJson: PackageJson,
options: UpdatePackageJsonOption
): PackageJson;
interface UpdatePackageJsonOption {
outputPath: string; // Build output directory
main?: string; // Main entry file path
generateExportsField?: boolean; // Generate exports field
additionalEntryPoints?: string[]; // Additional entry points for exports
format?: SupportedFormat[]; // Output formats (cjs, esm)
skipTypings?: boolean; // Skip generating typings field
generateLockfile?: boolean; // Generate matching lockfile
updateBuildableProjectDepsInPackageJson?: boolean; // Update buildable project dependencies
buildableProjectDepsInPackageJsonType?: DependencyType; // Dependency type for buildable projects
}
type SupportedFormat = 'cjs' | 'esm';
type DependencyType = 'dependencies' | 'devDependencies' | 'peerDependencies';Usage Examples:
import { updatePackageJson, getUpdatedPackageJsonContent } from "@nx/js";
// Update package.json in place
updatePackageJson({
outputPath: 'dist/libs/my-lib',
main: './src/index.js',
generateExportsField: true,
additionalEntryPoints: ['./src/utils.js'],
format: ['cjs', 'esm']
}, context, target, dependencies);
// Get updated content without writing
const originalPackageJson = { name: 'my-lib', version: '1.0.0' };
const updatedPackageJson = getUpdatedPackageJsonContent(originalPackageJson, {
outputPath: 'dist/libs/my-lib',
main: './src/index.js',
generateExportsField: true
});Generates modern package.json exports fields for multi-format packages with conditional exports.
/**
* Generates exports field for package.json
* @param options - Options containing output path, main file, and entry points
* @returns Exports field object for package.json
*/
function getExports(options: Pick<
UpdatePackageJsonOption,
'outputPath' | 'main' | 'additionalEntryPoints' | 'generateExportsField' | 'format'
>): Exports;
interface Exports {
[key: string]: string | ExportConditions;
}
interface ExportConditions {
types?: string; // TypeScript declaration file
import?: string; // ESM import path
require?: string; // CommonJS require path
default?: string; // Default fallback path
}Usage Example:
import { getExports } from "@nx/js";
const exports = getExports({
outputPath: 'dist/libs/my-lib',
main: './src/index.js',
additionalEntryPoints: ['./src/utils.js', './src/helpers.js'],
generateExportsField: true,
format: ['cjs', 'esm']
});
// Results in exports like:
// {
// ".": {
// "types": "./index.d.ts",
// "import": "./index.esm.js",
// "require": "./index.cjs.js",
// "default": "./index.js"
// },
// "./utils": {
// "types": "./utils.d.ts",
// "import": "./utils.esm.js",
// "require": "./utils.cjs.js"
// }
// }Creates additional entry points for libraries with multiple export paths.
/**
* Creates entry points from additional entry points configuration
* @param additionalEntryPoints - Array of additional entry point paths or undefined
* @param root - Project root directory
* @returns Array of matched entry point file paths
*/
function createEntryPoints(
additionalEntryPoints: undefined | string[],
root: string
): string[];Usage Example:
import { createEntryPoints } from "@nx/js";
const entryPoints = createEntryPoints([
'src/utils/*',
'src/helpers/index.ts'
], 'libs/my-lib');
// Returns resolved file paths like:
// ['src/utils/string-utils.ts', 'src/utils/date-utils.ts', 'src/helpers/index.ts']Resolves output directories for build artifacts and package placement.
/**
* Gets the output directory for build artifacts
* @param options - Options containing output path configuration
* @returns Resolved output directory path
*/
function getOutputDir(options: Pick<UpdatePackageJsonOption, 'outputPath'>): string;Usage Example:
import { getOutputDir } from "@nx/js";
const outputDir = getOutputDir({
outputPath: 'dist/libs/my-lib'
});
// Returns: 'dist/libs/my-lib'Copies and updates package.json files as part of the build process with dependency resolution.
/**
* Copies package.json to output directory with updates
* @param options - Copy configuration options
* @param context - Nx executor context
* @returns Promise resolving to copy result with success status
*/
function copyPackageJson(
options: CopyPackageJsonOptions,
context: ExecutorContext
): Promise<CopyPackageJsonResult>;
interface CopyPackageJsonOptions extends UpdatePackageJsonOption {
// Inherits all UpdatePackageJsonOption properties
}
interface CopyPackageJsonResult {
success: boolean; // Whether copy operation succeeded
stop?(): void; // Optional cleanup function
}Usage Example:
import { copyPackageJson } from "@nx/js";
const result = await copyPackageJson({
outputPath: 'dist/libs/my-lib',
main: './src/index.js',
generateExportsField: true,
generateLockfile: true
}, context);
if (result.success) {
console.log('Package.json copied successfully');
}
// Cleanup if needed
if (result.stop) {
result.stop();
}Creates lockfiles that match the workspace configuration for consistent dependency versions.
/**
* Creates lockfile matching workspace dependency versions
* @param packageJson - Package.json object to create lockfile for
* @param packageJsonPath - Path to package.json file
* @param options - Lockfile creation options
* @returns Promise resolving when lockfile is created
*/
function createLockFile(
packageJson: PackageJson,
packageJsonPath: string,
options?: CreateLockFileOptions
): Promise<void>;
/**
* Gets appropriate lockfile name for the current package manager
* @param packageManager - Package manager type
* @returns Lockfile filename (package-lock.json, yarn.lock, etc.)
*/
function getLockFileName(packageManager?: PackageManagerType): string;
interface CreateLockFileOptions {
packageManager?: PackageManagerType; // Package manager to use
skipInstall?: boolean; // Skip installing dependencies
}
type PackageManagerType = 'npm' | 'yarn' | 'pnpm' | 'bun';Usage Example:
import { createLockFile, getLockFileName } from "@nx/js";
// Create lockfile for npm
await createLockFile(
packageJson,
'dist/libs/my-lib/package.json',
{ packageManager: 'npm' }
);
// Get lockfile name
const lockfileName = getLockFileName('npm');
// Returns: 'package-lock.json'interface PackageJson {
name: string; // Package name
version: string; // Package version
description?: string; // Package description
main?: string; // Main entry point
module?: string; // ESM entry point
types?: string; // TypeScript declarations
exports?: Exports; // Modern exports field
scripts?: Record<string, string>; // npm scripts
dependencies?: Record<string, string>; // Runtime dependencies
devDependencies?: Record<string, string>; // Development dependencies
peerDependencies?: Record<string, string>; // Peer dependencies
[key: string]: any; // Additional fields
}
interface ProjectGraphProjectNode {
name: string; // Project name
type: string; // Project type
data: {
root: string; // Project root directory
sourceRoot?: string; // Source root directory
targets?: Record<string, any>; // Project targets
[key: string]: any; // Additional project data
};
}
interface DependentBuildableProjectNode {
name: string; // Project name
outputs: string[]; // Build output paths
node: ProjectGraphProjectNode; // Project graph node
}Create packages that support both CommonJS and ESM:
const exports = getExports({
outputPath: 'dist/libs/my-lib',
main: './src/index.js',
format: ['cjs', 'esm'],
generateExportsField: true
});
// Generates conditional exports for both formatsStructure packages with multiple entry points:
const updatedPackageJson = getUpdatedPackageJsonContent(originalPackageJson, {
outputPath: 'dist/libs/ui-components',
main: './src/index.js',
additionalEntryPoints: [
'./src/buttons/index.js',
'./src/forms/index.js',
'./src/layouts/index.js'
],
generateExportsField: true
});
// Allows imports like:
// import { Button } from '@myorg/ui-components/buttons';
// import { Form } from '@myorg/ui-components/forms';Control which dependencies are included in built packages:
updatePackageJson({
outputPath: 'dist/libs/my-lib',
updateBuildableProjectDepsInPackageJson: true,
buildableProjectDepsInPackageJsonType: 'dependencies'
}, context, target, dependencies);Create different package.json files for different environments:
// Production package.json
const prodPackageJson = createPackageJson('my-lib', graph, {
isProduction: true
});
// Development package.json with all dependencies
const devPackageJson = createPackageJson('my-lib', graph, {
isProduction: false
});Install with Tessl CLI
npx tessl i tessl/npm-nx--js