CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-nrwl--devkit

Legacy wrapper providing comprehensive Nx devkit utilities for creating plugins, generators, and executors

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

json-utilities.mddocs/

JSON Utilities

Comprehensive JSON handling utilities for both virtual tree operations and filesystem I/O. These utilities provide consistent JSON parsing, serialization, and file manipulation with support for comments and custom formatting options.

Capabilities

Tree-based JSON Operations

Functions for working with JSON files in the virtual Tree filesystem.

/**
 * Read and parse JSON from the virtual tree
 * @template T - Expected JSON structure type
 * @param tree - Virtual file system tree
 * @param path - Path to the JSON file
 * @returns Parsed JSON object
 */
function readJson<T = any>(tree: Tree, path: string): T;

/**
 * Serialize and write JSON to the virtual tree
 * @template T - JSON data type
 * @param tree - Virtual file system tree
 * @param path - Path where to write the JSON file
 * @param value - Object to serialize to JSON
 * @param options - Optional serialization options
 */
function writeJson<T = any>(
  tree: Tree, 
  path: string, 
  value: T,
  options?: JsonSerializeOptions
): void;

/**
 * Update JSON file using an updater function
 * @template T - Current JSON structure type
 * @template U - Updated JSON structure type
 * @param tree - Virtual file system tree
 * @param path - Path to the JSON file
 * @param updater - Function to transform the JSON
 * @param options - Optional serialization options
 * @returns The updated JSON value
 */
function updateJson<T = any, U = T>(
  tree: Tree,
  path: string,
  updater: (json: T) => U,
  options?: JsonSerializeOptions
): U;

Usage Examples:

import { Tree, readJson, writeJson, updateJson } from "@nrwl/devkit";

function manageJsonFiles(tree: Tree) {
  // Read package.json
  const packageJson = readJson(tree, 'package.json');
  console.log('Package name:', packageJson.name);
  
  // Write new JSON file
  const newConfig = {
    version: '1.0.0',
    features: ['feature1', 'feature2'],
    settings: {
      debug: true,
      timeout: 30000
    }
  };
  writeJson(tree, 'config/app.json', newConfig);
  
  // Update existing JSON file
  updateJson(tree, 'package.json', (json) => {
    return {
      ...json,
      scripts: {
        ...json.scripts,
        'custom-build': 'nx build --prod'
      }
    };
  });
}

File System JSON Operations

Functions for direct JSON file I/O on the filesystem.

/**
 * Read and parse JSON file from filesystem
 * @template T - Expected JSON structure type
 * @param path - File path to read
 * @param options - Optional parse options
 * @returns Parsed JSON object
 */
function readJsonFile<T = any>(path: string, options?: JsonParseOptions): T;

/**
 * Serialize and write JSON file to filesystem
 * @template T - JSON data type
 * @param path - File path to write
 * @param data - Object to serialize to JSON
 * @param options - Optional serialization options
 */
function writeJsonFile<T = any>(
  path: string, 
  data: T, 
  options?: JsonSerializeOptions
): void;

Usage Examples:

import { readJsonFile, writeJsonFile } from "@nrwl/devkit";

function handleJsonFiles() {
  // Read JSON file from disk
  const config = readJsonFile('config/settings.json');
  
  // Modify and write back
  config.lastUpdated = new Date().toISOString();
  writeJsonFile('config/settings.json', config, {
    spaces: 2
  });
  
  // Read with error handling
  try {
    const userConfig = readJsonFile('config/user.json');
    console.log('User config loaded:', userConfig);
  } catch (error) {
    console.warn('User config not found, using defaults');
  }
}

JSON Parsing and Serialization

Low-level JSON processing functions with advanced options.

/**
 * Parse JSON string with support for comments and custom options
 * @template T - Expected JSON structure type
 * @param input - JSON string to parse
 * @param options - Parse options
 * @returns Parsed JSON object
 */
function parseJson<T = any>(input: string, options?: JsonParseOptions): T;

/**
 * Serialize object to JSON string with formatting options
 * @template T - Object type to serialize
 * @param input - Object to serialize
 * @param options - Serialization options
 * @returns Formatted JSON string
 */
function serializeJson<T = any>(input: T, options?: JsonSerializeOptions): string;

/**
 * Remove comments from JSON string
 * @param text - JSON string with comments
 * @returns JSON string without comments
 */
function stripJsonComments(text: string): string;

Usage Examples:

import { 
  parseJson, 
  serializeJson, 
  stripJsonComments,
  JsonParseOptions 
} from "@nrwl/devkit";

function processJsonData() {
  // Parse JSON with comments
  const jsonWithComments = `
    {
      // This is a comment
      "name": "my-app",
      "version": "1.0.0",
      /* Multi-line comment */
      "dependencies": {}
    }
  `;
  
  const config = parseJson(jsonWithComments, {
    allowTrailingComma: true,
    disallowComments: false
  });
  
  // Serialize with custom formatting
  const formatted = serializeJson(config, {
    spaces: 4,
    quote: '"'
  });
  
  console.log('Formatted JSON:', formatted);
  
  // Strip comments manually
  const withoutComments = stripJsonComments(jsonWithComments);
  console.log('No comments:', withoutComments);
}

JSON Options and Types

Configuration interfaces for JSON operations.

/**
 * Options for JSON parsing
 */
interface JsonParseOptions {
  /** Whether to expect an array at the root */
  expectComments?: boolean;
  /** Whether to allow trailing commas */
  allowTrailingComma?: boolean;
  /** Whether to disallow comments */
  disallowComments?: boolean;
}

/**
 * Options for JSON serialization
 */
interface JsonSerializeOptions {
  /** Number of spaces for indentation or '\t' for tabs */
  spaces?: number | string;
  /** Quote character to use */
  quote?: '"' | "'";
  /** Whether to quote property names */
  quoteNames?: boolean;
  /** Custom replacer function */
  replacer?: (key: string, value: any) => any;
}

Usage Examples:

import { 
  JsonParseOptions, 
  JsonSerializeOptions,
  parseJson,
  serializeJson 
} from "@nrwl/devkit";

function customJsonHandling() {
  const parseOptions: JsonParseOptions = {
    allowTrailingComma: true,
    disallowComments: false
  };
  
  const serializeOptions: JsonSerializeOptions = {
    spaces: 2,
    quote: '"',
    replacer: (key, value) => {
      // Don't serialize internal properties
      if (key.startsWith('_')) return undefined;
      return value;
    }
  };
  
  const data = {
    name: 'test',
    _internal: 'hidden',
    values: [1, 2, 3]
  };
  
  const jsonString = serializeJson(data, serializeOptions);
  console.log('Serialized:', jsonString);
  // Output: { "name": "test", "values": [1, 2, 3] }
  
  const parsed = parseJson(jsonString, parseOptions);
  console.log('Parsed:', parsed);
}

Advanced JSON Operations

Specialized functions for complex JSON manipulation scenarios.

/**
 * Deep merge JSON objects
 * @param target - Target object to merge into
 * @param sources - Source objects to merge from
 * @returns Merged object
 */
function deepMergeJson<T = any>(target: T, ...sources: Partial<T>[]): T;

/**
 * Compare two JSON objects for structural equality
 * @param a - First object
 * @param b - Second object
 * @returns Whether objects are structurally equal
 */
function isJsonEqual(a: any, b: any): boolean;

/**
 * Get JSON schema for an object
 * @param obj - Object to generate schema for
 * @returns JSON schema object
 */
function getJsonSchema(obj: any): Record<string, any>;

Usage Examples:

import { deepMergeJson, isJsonEqual } from "@nrwl/devkit";

function advancedJsonOperations() {
  const baseConfig = {
    name: 'app',
    features: ['auth'],
    settings: {
      theme: 'dark',
      timeout: 5000
    }
  };
  
  const overrides = {
    features: ['auth', 'notifications'],
    settings: {
      timeout: 10000,
      debug: true
    }
  };
  
  // Deep merge configurations
  const merged = deepMergeJson(baseConfig, overrides);
  console.log('Merged config:', merged);
  // Result: {
  //   name: 'app',
  //   features: ['auth', 'notifications'],
  //   settings: { theme: 'dark', timeout: 10000, debug: true }
  // }
  
  // Compare configurations
  const isEqual = isJsonEqual(baseConfig, merged);
  console.log('Configs equal:', isEqual); // false
}

Install with Tessl CLI

npx tessl i tessl/npm-nrwl--devkit

docs

executors.md

generators.md

index.md

json-utilities.md

package-management.md

plugins.md

project-configuration.md

project-graph.md

string-path-utilities.md

testing-utilities.md

tree-filesystem.md

tile.json