### Initialize GTS Project Programmatically Source: https://context7.com/google/gts/llms.txt Use the `init` function from `src/init.ts` to programmatically set up a new TypeScript project. This function reads or creates `package.json`, injects GTS scripts and dependencies, and generates necessary configuration files. Ensure `gtsRootDir` is correctly set to the GTS installation path. ```typescript import {init} from 'gts/build/src/init'; import {Options} from 'gts/build/src/cli'; const options: Options = { dryRun: false, // set true to preview without writing gtsRootDir: require.resolve('gts/package.json').replace('/package.json', ''), targetRootDir: process.cwd(), yes: true, // auto-accept all prompts no: false, logger: console, yarn: false, }; async function setup() { const success = await init(options); if (success) { console.log('GTS initialized successfully.'); // Result: package.json updated, tsconfig.json written, // eslint.config.js written, eslint.ignores.js written, // .prettierrc.js written, .editorconfig written, // src/index.ts template installed (if src/ was empty), // npm install --ignore-scripts run. } else { console.error('GTS initialization failed or was cancelled.'); process.exit(1); } } setup(); ``` -------------------------------- ### Initialize Project with GTS Source: https://context7.com/google/gts/llms.txt Scaffolds a new or existing project with GTS configuration files, npm scripts, and dependencies. Use -y to accept all prompts automatically. ```bash npx gts init -y ``` ```bash npx gts init --dry-run ``` ```bash npx gts init --yarn -y ``` ```json { "scripts": { "lint": "gts lint", "fix": "gts fix", "clean": "gts clean", "compile": "tsc", "prepare": "npm run compile", "pretest": "npm run compile", "posttest":"npm run lint" }, "devDependencies": { "gts": "^7.0.0", "typescript": "^5.6.3", "@types/node": "^22.7.5" } } ``` ```json { "extends": "./node_modules/gts/tsconfig-google.json", "compilerOptions": { "rootDir": ".", "outDir": "build" }, "include": ["src/**/*.ts", "test/**/*.ts"] } ``` ```javascript module.exports = [...customConfig, ...require('gts')]; ``` -------------------------------- ### Initialize gts in a Project Source: https://github.com/google/gts/blob/main/README.md Run this command to set up gts in your project. It adds a tsconfig.json, devDependencies, and scripts to your package.json. ```sh npx gts init ``` -------------------------------- ### init(options) — Initialize project programmatically Source: https://context7.com/google/gts/llms.txt The `init` function from `src/init.ts` can be called from Node.js scripts to read or create `package.json`, inject GTS scripts and dependencies, and generate all necessary configuration files for a TypeScript project. ```APIDOC ## Programmatic API: `init(options)` — Initialize project programmatically The `init` function from `src/init.ts` can be called from Node.js scripts. It reads or creates `package.json`, injects GTS scripts and dependencies, and generates all config files. ```typescript import {init} from 'gts/build/src/init'; import {Options} from 'gts/build/src/cli'; const options: Options = { dryRun: false, // set true to preview without writing gtsRootDir: require.resolve('gts/package.json').replace('/package.json', ''), targetRootDir: process.cwd(), yes: true, // auto-accept all prompts no: false, logger: console, yarn: false, }; async function setup() { const success = await init(options); if (success) { console.log('GTS initialized successfully.'); // Result: package.json updated, tsconfig.json written, // eslint.config.js written, eslint.ignores.js written, // .prettierrc.js written, .editorconfig written, // src/index.ts template installed (if src/ was empty), // npm install --ignore-scripts run. } else { console.error('GTS initialization failed or was cancelled.'); process.exit(1); } } setup(); ``` ``` -------------------------------- ### Use ESLint CLI Directly Source: https://github.com/google/gts/blob/main/README.md If not using the gts CLI, you can leverage the ESLint CLI directly with the gts configuration. ```sh eslint --fix ``` -------------------------------- ### Configure gts with pre-commit Source: https://github.com/google/gts/blob/main/README.md Integrate gts into your Git workflow using the pre-commit framework by adding this configuration to your .pre-commit-config.yaml. ```yaml repos: - repo: https://github.com/google/gts rev: '' # Use the sha / tag you want to point at hooks: - id: gts ``` -------------------------------- ### Clean Build Output with GTS Source: https://context7.com/google/gts/llms.txt Recursively deletes the directory specified by compilerOptions.outDir in tsconfig.json. Requires outDir to be set and not equal to "." to prevent accidental source deletion. Exits with code 1 on error. ```bash npm run clean # or directly: npx gts clean ``` ```json { "compilerOptions": { "outDir": "build" } } ``` ```text Output: Removing build/ ... Result: ./build/ directory is deleted ``` ```text ERROR: The clean command requires compilerOptions.outDir to be defined in tsconfig.json. Exit code 1 ``` ```text ERROR: compilerOptions.outDir cannot use the value ".". That would delete all sources. Exit code 1 ``` -------------------------------- ### Configure ESLint with gts Source: https://github.com/google/gts/blob/main/README.md Extend the shared gts ESLint configuration in your project's eslint.config.js file. ```javascript module.exports = [ ...require('gts'), ]; ``` -------------------------------- ### ESLint Configuration with GTS Source: https://context7.com/google/gts/llms.txt Consume the GTS ESLint flat-config array directly in your `eslint.config.js` to apply Google TypeScript Style rules, Prettier integration, and Node.js plugin rules. Project-specific overrides can be applied. ```javascript // eslint.config.js — minimal usage (generated by gts init) module.exports = [ ...require('gts'), ]; ``` ```javascript // eslint.config.js — with project-specific overrides const gtsConfig = require('gts'); const defineConfig = require('eslint/config').defineConfig; module.exports = defineConfig([ ...gtsConfig, { // Override: allow console.log in scripts directory files: ['scripts/**/*.ts'], rules: { 'no-console': 'off', }, }, { // Override: relax trailing comma rule in config files files: ['*.config.js'], rules: { 'prettier/prettier': ['error', {trailingComma: 'es5'}], }, }, ]); ``` -------------------------------- ### Add gts Badge to README Source: https://github.com/google/gts/blob/main/README.md Include this Markdown snippet in your README to display a badge indicating your project uses Google's code style. ```markdown [![Code Style: Google](https://img.shields.io/badge/code%20style-google-blueviolet.svg)](https://github.com/google/gts) ``` -------------------------------- ### getTSConfig(rootDir) — Read and resolve tsconfig.json Source: https://context7.com/google/gts/llms.txt The `getTSConfig` function reads a `tsconfig.json` from the specified directory, fully resolves its `extends` chain (including transitive parents), and returns the merged compiler options object. It throws an error if circular references are detected. ```APIDOC ## Programmatic API: `getTSConfig(rootDir)` — Read and resolve tsconfig.json Reads a `tsconfig.json` from the given directory, fully resolves any `extends` chain (including transitive parents), and returns the merged compiler options object. Throws on circular references. ```typescript import {getTSConfig} from 'gts/build/src/util'; async function inspectConfig() { try { const config = await getTSConfig(process.cwd()); console.log('Resolved compiler options:', config.compilerOptions); // Example output for a project extending gts/tsconfig-google.json: // { // allowUnreachableCode: false, // strict: true, // target: 'ES2022', // module: 'commonjs', // outDir: 'build', // rootDir: '.', // sourceMap: true, // ... // } if (config.compilerOptions && (config.compilerOptions as any).outDir) { console.log('Build output dir:', (config.compilerOptions as any).outDir); } } catch (e) { // Thrown when tsconfig.json not found or circular extends reference console.error('Failed to read tsconfig:', e); } } inspectConfig(); ``` ``` -------------------------------- ### Base TypeScript Compiler Configuration (`tsconfig-google.json`) Source: https://context7.com/google/gts/llms.txt The canonical Google TypeScript compiler options, designed to be extended by project-level `tsconfig.json` files. Enforces strict type-checking, ES2022 output, composite project support, and source maps. ```json // node_modules/gts/tsconfig-google.json (shipped with the package) { "compilerOptions": { "allowUnreachableCode": false, "allowUnusedLabels": false, "composite": true, "forceConsistentCasingInFileNames": true, "lib": ["ES2023"], "module": "commonjs", "noEmitOnError": true, "noFallthroughCasesInSwitch": true, "noImplicitReturns": true, "pretty": true, "sourceMap": true, "stripInternal": true, "strict": true, "target": "ES2022" }, "exclude": ["node_modules"] } ``` ```json // tsconfig.json — project file extending the Google base (generated by gts init) { "extends": "./node_modules/gts/tsconfig-google.json", "compilerOptions": { "rootDir": ".", "outDir": "build" }, "include": ["src/**/*.ts", "test/**/*.ts"] } ``` -------------------------------- ### Fix Lint Issues with GTS Source: https://context7.com/google/gts/llms.txt Applies automatic corrections for formatting and fixable lint rules in-place using ESLint with --fix. Use --dry-run to preview changes. Exits with code 0 on success, 1 if ESLint errors remain. ```bash npm run fix # or directly: npx gts fix ``` ```bash npx gts fix src/server.ts src/util.ts ``` ```bash npx gts fix --dry-run ``` ```typescript // Example: before fix (src/index.ts) // var x = "hello" // const obj = {a:1,b:2} ``` ```typescript // Example: after fix (src/index.ts) // const x = 'hello'; // const obj = {a: 1, b: 2}; // // Exit code 0 on success, 1 if ESLint errors remain after fixing. ``` -------------------------------- ### Prettier Formatting Rules with GTS Source: https://context7.com/google/gts/llms.txt The Prettier configuration shipped with GTS implements Google's preferred formatting conventions. Extend it in your own `.prettierrc.js` or use it directly for formatting. ```javascript // .prettierrc.js — generated by gts init module.exports = { ...require('gts/.prettierrc.json'), }; // Effective rules (from node_modules/gts/.prettierrc.json): // { // "bracketSpacing": false, // {a:1} not { a: 1 } // "singleQuote": true, // 'hello' not "hello" // "trailingComma": "all", // trailing commas everywhere (ES5+) // "arrowParens": "avoid" // x => x not (x) => x // } // Example: format a file directly with Prettier using gts config // npx prettier --config .prettierrc.js --write src/index.ts // Before formatting: // const greet = (name: string) => { return "Hello " + name; } // After formatting: // const greet = (name: string) => 'Hello ' + name; ``` -------------------------------- ### Read and Resolve tsconfig.json Programmatically Source: https://context7.com/google/gts/llms.txt The `getTSConfig` function from `src/util.ts` reads a `tsconfig.json` file from the specified directory, resolves its entire `extends` chain, and returns the merged compiler options. It throws an error if circular references are detected or if `tsconfig.json` is not found. ```typescript import {getTSConfig} from 'gts/build/src/util'; async function inspectConfig() { try { const config = await getTSConfig(process.cwd()); console.log('Resolved compiler options:', config.compilerOptions); // Example output for a project extending gts/tsconfig-google.json: // { // allowUnreachableCode: false, // strict: true, // target: 'ES2022', // module: 'commonjs', // outDir: 'build', // rootDir: '.', // sourceMap: true, // ... // } if (config.compilerOptions && (config.compilerOptions as any).outDir) { console.log('Build output dir:', (config.compilerOptions as any).outDir); } } catch (e) { // Thrown when tsconfig.json not found or circular extends reference console.error('Failed to read tsconfig:', e); } } inspectConfig(); ``` -------------------------------- ### Pre-commit Hook Integration with GTS Source: https://context7.com/google/gts/llms.txt GTS ships a pre-commit hook definition compatible with the pre-commit framework. This runs `gts lint` automatically on staged TypeScript and JavaScript files before every commit. ```yaml # .pre-commit-config.yaml — add to your repository root repos: - repo: https://github.com/google/gts rev: 'v7.0.0' # pin to a specific release tag or SHA hooks: - id: gts # Hook behavior (from .pre-commit-hooks.yaml in gts): # - Runs: gts lint # - Applies to: .js, .jsx, .ts, .tsx files # - Requires serial execution (no parallel runs) # - Uses system node version # Install hooks after adding the config: # pre-commit install # Run manually against all files: # pre-commit run gts --all-files # Example output on violation: # gts..................................................................Failed # - hook id: gts # - exit code: 1 # /path/to/file.ts # 5:3 error 'var' declarations are not allowed no-var ``` -------------------------------- ### Lint Code with GTS Source: https://context7.com/google/gts/llms.txt Runs ESLint to check for style and lint violations in TypeScript and JavaScript files. Exits with code 1 if violations are found. Can lint specific files or use glob patterns. ```bash npm run lint # or directly: npx gts lint ``` ```bash npx gts lint src/server.ts src/util.ts ``` ```bash npx gts lint 'src/**/*.ts' ``` ```text /project/src/index.ts 3:1 error 'var' declarations are not allowed no-var 7:5 error Missing semicolon prettier/prettier ✖ 2 problems (2 errors, 0 warnings) Process exits with code 1 ``` ```text (no output, exits 0) ``` -------------------------------- ### Lint Individual TypeScript Files Source: https://github.com/google/gts/blob/main/README.md Use the gts lint command to check formatting and style issues on specific files or using glob patterns. ```sh gts lint index.ts ``` ```sh gts lint one.ts two.ts three.ts ``` ```sh gts lint *.ts ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.