### Command-line argument examples Source: https://knip.dev/explanations/plugins Examples of CLI commands that specify entry files or configuration files for Knip to process. ```bash node --loader tsx scripts/deploy.ts playwright test -c playwright.web.config.ts ``` -------------------------------- ### Use preprocessors with Knip Source: https://knip.dev/reference/cli Examples of applying preprocessors to Knip results using local files or installed packages. ```bash knip --preprocessor ./my-preprocessor.ts ``` ```bash knip --preprocessor preprocessor-package ``` -------------------------------- ### Install unlisted dependencies Source: https://knip.dev/features/auto-fix Commands to install missing dependencies reported by Knip. ```bash npm install unlisted-package ``` ```bash pnpm add unlisted-package ``` ```bash bun add unlisted-package ``` ```bash yarn add unlisted-package ``` -------------------------------- ### Example Astro configuration Source: https://knip.dev/writing-a-plugin A sample configuration file for Astro using the Starlight integration. ```typescript import starlight from '@astrojs/starlight'; import { defineConfig } from 'astro/config'; export default defineConfig({ integrations: [ starlight({ components: { Head: './src/components/Head.astro', Footer: './src/components/Footer.astro', }, }), ], }); ``` -------------------------------- ### Manually Install Knip Source: https://knip.dev/overview/getting-started Install Knip and its required peer dependencies as development dependencies. ```shell npm install -D knip typescript @types/node ``` ```shell pnpm add -D knip typescript @types/node ``` ```shell bun add -D knip typescript @types/node ``` ```shell yarn add -D knip typescript @types/node ``` -------------------------------- ### ESLint Configuration Example Source: https://knip.dev/explanations/plugins A minimal ESLint configuration file demonstrating how plugins and extended configs are defined. ```json { "extends": ["airbnb", "prettier"], "plugins": ["@typescript-eslint"] } ``` -------------------------------- ### Start MCP Server Source: https://knip.dev/reference/integrations Command to initiate the standalone MCP server for coding agents. ```bash npx @knip/mcp ``` -------------------------------- ### Custom Project Configuration Source: https://knip.dev/overview/configuration Example of a custom configuration file including a JSON schema reference and specific entry/project patterns. ```json { "$schema": "https://unpkg.com/knip@6/schema.json", "entry": ["src/index.ts", "scripts/{build,create}.js"], "project": ["src/**/*.ts", "scripts/**/*.js"] } ``` -------------------------------- ### Example nyc configuration file Source: https://knip.dev/writing-a-plugin A sample JSON configuration file that the nyc plugin is designed to process. ```json { "extends": "@istanbuljs/nyc-config-typescript", "check-coverage": true } ``` -------------------------------- ### HTML script reference example Source: https://knip.dev/guides/handling-issues Example of an HTML file referencing a script that Knip might not automatically resolve. ```html ``` -------------------------------- ### Vitest Configuration Example Source: https://knip.dev/explanations/plugins A minimal Vitest configuration file using the defineConfig helper to specify test environment and coverage providers. ```javascript import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { coverage: { provider: 'istanbul', }, environment: 'happy-dom', }, }); ``` -------------------------------- ### Install Knip v6 Source: https://knip.dev/blog/knip-v6 Command to upgrade to the latest version of Knip. ```bash npm install -D knip@latest ``` -------------------------------- ### Configure package.json for binary execution Source: https://knip.dev/guides/handling-issues Example of a package.json configuration where a script correctly references a binary provided by a listed devDependency. ```json { "name": "lib", "scripts": { "commitlint": "commitlint --edit" }, "devDependencies": { "@commitlint/cli": "*" } } ``` -------------------------------- ### Handle unconfigured workspaces Source: https://knip.dev/reference/configuration-hints Messages and configuration examples for resolving unused files in monorepo workspaces. ```text Create knip.json configuration file with workspaces["packages/app"] object (42 unused files) ``` ```text Add entry and/or refine project files in workspaces["packages/app"] (42 unused files) ``` ```json { "workspaces": { "packages/app": { "entry": ["src/App.tsx"], "project": ["src/**/*.ts"] } } } ``` -------------------------------- ### Dynamic import specifier example Source: https://knip.dev/guides/handling-issues Example of a dynamic import that Knip cannot resolve automatically. ```javascript const entry = await import(path.join(baseDir, 'entry.ts')); ``` -------------------------------- ### Install Knip Canary via NPM Source: https://knip.dev/blog/slim-down-to-speed-up Use this command to install the latest canary version of Knip as a development dependency. ```bash npm install -D knip@canary ``` -------------------------------- ### Parse package.json entry points Source: https://knip.dev/features/script-parser Example of how Knip identifies entry files from main, exports, bin, and scripts fields in package.json. ```json { "name": "my-package", "main": "index.js", "exports": { "./lib": { "import": "./dist/index.mjs", "require": "./dist/index.cjs" } }, "bin": { "program": "bin/cli.js" }, "scripts": { "build": "rollup src/entry.ts", "start": "node --loader tsx server.ts" } } ``` -------------------------------- ### Vite configuration file example Source: https://knip.dev/explanations/plugins A Vite configuration file that Knip parses to identify both direct imports and indirect dependencies defined within the configuration object. ```typescript import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig(async ({ mode, command }) => { return { plugins: [react()], test: { setupFiles: ['./setup-tests.ts'], environment: 'happy-dom', coverage: { provider: 'c8', }, }, }; }); ``` -------------------------------- ### Next.js Configuration with Environment Dependency Source: https://knip.dev/blog/state-of-knip A configuration example that relies on environment variables, which can cause runtime errors during Knip analysis if variables are missing. ```javascript const nextConfig = { pageExtensions: ['page.tsx'], env: { BASE_URL: process.env.BASE_URL.toLowerCase(), }, }; export default nextConfig; ``` -------------------------------- ### Unsupported script argument configuration Source: https://knip.dev/guides/handling-issues Example of a package.json script that uses arguments Knip may not recognize. ```json { "name": "my-lib", "version": "1.0.0", "scripts": { "build": "unknown-build-cli --entry production.ts" } } ``` -------------------------------- ### Vitest Script Configuration in package.json Source: https://knip.dev/blog/state-of-knip An example of a script command that requires Knip to parse custom CLI arguments and workspace paths. ```json { "scripts": { "test": "yarn --cwd packages/frontend vitest -c vitest.components.config.ts" } } ``` -------------------------------- ### Implement a Custom Preprocessor Source: https://knip.dev/features/reporters An example implementation of a preprocessor that modifies issues and counters. ```typescript import type { Preprocessor } from 'knip'; const preprocess: Preprocessor = function (options) { // modify options.issues and options.counters return options; }; export default preprocess; ``` -------------------------------- ### Detect CLI arguments and dependencies Source: https://knip.dev/features/script-parser Example showing how Knip extracts dependencies and configuration files from CLI arguments within package.json scripts. ```json { "name": "my-lib", "scripts": { "start": "node --import tsx/esm run.ts", "bundle": "tsup -c tsup.lib.config.ts", "type-check": "tsc -p tsconfig.app.json" } } ``` -------------------------------- ### Define Module Exports Source: https://knip.dev/guides/namespace-imports Example module containing multiple exports to be imported via namespace. ```javascript export const version = 'v5'; export const getRocket = () => '🚀'; ``` -------------------------------- ### Import from monorepo workspace Source: https://knip.dev/features/source-mapping Example of an internal workspace import that Knip attempts to map to source files. ```javascript import { helper } from '@org/shared'; ``` -------------------------------- ### Identify simple export/import patterns Source: https://knip.dev/blog/slim-down-to-speed-up Example of a straightforward export and import match that Knip can resolve without complex analysis. ```typescript import { MyThing } from './thing.ts'; ``` ```typescript export const MyThing = 'cool'; ``` -------------------------------- ### Configure package.json exports for source mapping Source: https://knip.dev/features/source-mapping Define entry points and internal paths in package.json to guide Knip's source mapping process. ```json { "name": "my-workspace", "main": "index.js", "exports": { ".": "./src/entry.js", "./feat": "./lib/feat.js", "./public": "./dist/app.js", "./public/*": "./dist/*.js", "./public/*.js": "./dist/*.js", "./dist/internal/*": null, }, } ``` -------------------------------- ### Configure TypeScript plugin settings Source: https://knip.dev/reference/faq Example of a tsconfig.json file used by the Knip TypeScript plugin to extract dependencies from extends and compilerOptions. ```json { "extends": "@tsconfig/node20/tsconfig.json", "compilerOptions": { "jsxImportSource": "hastscript/svg" } } ``` -------------------------------- ### Configure Playwright test settings Source: https://knip.dev/explanations/plugins Example of a Playwright configuration file that the plugin parses to extract entry patterns. ```typescript import type { PlaywrightTestConfig } from '@playwright/test'; const config: PlaywrightTestConfig = { testDir: 'integration', testMatch: ['**/*-test.ts'], }; export default config; ``` -------------------------------- ### Run Knip Without Installation Source: https://knip.dev/overview/getting-started Execute Knip directly using package manager runners. Requires typescript and @types/node to be present in the project. ```shell npx knip ``` ```shell pnpm dlx knip ``` ```shell bunx knip ``` -------------------------------- ### Trace external library consumption Source: https://knip.dev/guides/handling-issues Example demonstrating how external libraries like @loadable/component might obscure export usage, requiring Knip to trace references through library APIs. ```javascript import loadable from '@loadable/component'; export const DynamicApple = dynamic(() => import('./components.js').then(mod => mod.Apple) ); export const LoadableOrange = loadable(() => import('./components.js'), { resolveComponent: components => components.Orange, }); ``` ```javascript export const Apple = () => 'Apple'; export const Orange = () => 'Orange'; ``` -------------------------------- ### Initialize a new plugin Source: https://knip.dev/writing-a-plugin Use the create-plugin script to scaffold source files, tests, and fixtures for a new plugin. ```bash cd packages/knip pnpm create-plugin --name tool ``` -------------------------------- ### Initialize Knip Configuration Source: https://knip.dev/overview/getting-started Use the create command to automatically set up a Knip configuration in your project. ```shell npm init @knip/config ``` ```shell pnpm create @knip/config ``` ```shell bun create @knip/config ``` ```shell yarn create @knip/config ``` -------------------------------- ### Manage top-level entry and project keys Source: https://knip.dev/reference/configuration-hints Instructions and configuration for moving top-level keys into workspace-specific configurations. ```text Remove, or move unused top-level entry to one of "workspaces" Remove, or move unused top-level project to one of "workspaces" ``` ```json { "entry": ["src/App.tsx"], // move entry/project from here... ↴ "project": ["src/**/*.ts"], "workspaces": { ".": { "entry": ["src/App.tsx"], // ...to the correct workspace(s) ↲ "project": ["src/**/*.ts"], }, }, } ``` -------------------------------- ### Use positional arguments as entry points Source: https://knip.dev/writing-a-plugin/argument-parsing Treat the first positional argument as an entry point. ```javascript { positional: true; } ``` -------------------------------- ### Configure Entry and Project Files Source: https://knip.dev/features/integrated-monorepos Define entry points and project file patterns to ensure Knip correctly identifies files in an integrated monorepo structure. ```json { "entry": ["{apps,libs}/**/src/index.{ts,tsx}"], "project": ["{apps,libs}/**/src/**/*.{ts,tsx}"] } ``` -------------------------------- ### Markdown report format Source: https://knip.dev/features/reporters Example of the Markdown output generated by the built-in reporter. ```markdown # Knip report ## Unused files (1) - src/unused.ts ## Unlisted dependencies (2) | Name | Location | Severity | | :-------------- | :---------------- | :------- | | unresolved | src/index.ts:8:23 | error | | @org/unresolved | src/index.ts:9:23 | error | ## Unresolved imports (1) | Name | Location | Severity | | :----------- | :----------------- | :------- | | ./unresolved | src/index.ts:10:12 | error | ``` -------------------------------- ### JSON output structure Source: https://knip.dev/features/reporters Example of the JSON structure returned by the reporter, containing an issues array. ```json { "issues": [ { "file": "src/legacy.ts", "files": [{ "name": "src/legacy.ts" }] }, { "file": "src/math.ts", "exports": [{ "name": "factorial", "line": 12, "col": 14, "pos": 256 }], "types": [{ "name": "Radians", "line": 20, "col": 13, "pos": 410 }] }, { "file": "package.json", "dependencies": [{ "name": "lodash" }], "unlisted": [{ "name": "rimraf" }] } ] } ``` -------------------------------- ### Run plugin tests Source: https://knip.dev/writing-a-plugin Execute tests for the newly created plugin using Node.js or Bun. ```bash node --test test/plugins/tool.test.ts bun test test/plugins/tool.test.ts ``` -------------------------------- ### Define TypeScript Namespaces Source: https://knip.dev/blog/knip-v6 Example of TS namespace members that are now correctly analyzed in Knip v6. ```typescript export namespace MyNamespace { export const myName = 'knip'; // we were ignored in v5, export type MyType = string; // yet in v6 we are included } ``` -------------------------------- ### Configure preprocessor options Source: https://knip.dev/reference/cli Pass additional configuration to a preprocessor as a JSON string. ```bash knip --preprocessor ./preproc.ts --preprocessor-options '{"key":"value"}' ``` -------------------------------- ### Run Knip with Bun Source: https://knip.dev/reference/cli Execute Knip using the Bun runtime instead of Node.js. ```bash knip-bun ``` -------------------------------- ### Handle unconfigured projects Source: https://knip.dev/reference/configuration-hints Messages displayed when a project lacks a configuration file or has incomplete configuration. ```text Create knip.json configuration file, and add entry and/or refine project files (42 unused files) ``` ```text Add entry and/or refine project files (42 unused files) ``` -------------------------------- ### Define a Tailwind plugin Source: https://knip.dev/writing-a-plugin A complete example of a Knip plugin that identifies Tailwind configuration files as entry points. ```typescript import type { IsPluginEnabled, Plugin } from '../../types/config.js'; import { hasDependency } from '../../util/plugin.js'; const title = 'Tailwind'; const enablers = ['tailwindcss']; const isEnabled: IsPluginEnabled = ({ dependencies }) => hasDependency(dependencies, enablers); const entry = ['tailwind.config.{js,cjs,mjs,ts}']; const plugin: Plugin = { title, enablers, isEnabled, entry, }; export default plugin; ``` -------------------------------- ### Define JSDoc/TSDoc tags Source: https://knip.dev/reference/cli Example of tagging exported values with JSDoc/TSDoc tags for use with the --tags flag. ```typescript /** * Description of my exported value * * @type number * @internal Important matters * @lintignore */ export const myExport = 1; ``` -------------------------------- ### Run Knip Source: https://knip.dev/overview/getting-started Execute the linting process to identify unused project assets. ```shell npm run knip ``` ```shell pnpm knip ``` ```shell bun knip ``` ```shell yarn knip ``` -------------------------------- ### Debug path alias errors Source: https://knip.dev/reference/known-issues Example output when a configuration file fails to resolve TypeScript path aliases. ```bash $ knip Analyzing workspace .... Error loading .../cypress.config.ts Reason: Cannot find module '@alias/name' Require stack: - .../cypress.config.ts ``` -------------------------------- ### Define configuration file arguments Source: https://knip.dev/writing-a-plugin/argument-parsing Identify arguments that represent configuration file paths. ```javascript { config: true; } ``` ```javascript { config: ['p']; } ``` -------------------------------- ### Debug Knip configuration loading Source: https://knip.dev/reference/known-issues Run Knip to identify errors when loading configuration files. ```bash $ knip ERROR: Error loading vite.config.ts ``` -------------------------------- ### Configure CODEOWNERS path Source: https://knip.dev/features/reporters Use --reporter-options to point the reporter to a custom CODEOWNERS file location. ```bash knip --reporter json --reporter-options '{"codeowners":"docs/CODEOWNERS"}' ``` -------------------------------- ### Conditional dependency in Playwright configuration Source: https://knip.dev/guides/handling-issues Example of a configuration file where a dependency is added conditionally, which may cause Knip to miss the reference. ```typescript import { defineConfig } from '@playwright/test'; const reporters: any[] = [['list']]; if (process.env.REPORT_PORTAL_ENABLED) { reporters.push(['@reportportal/agent-js-playwright', config]); } export default defineConfig({ reporter: reporters, }); ``` -------------------------------- ### Custom Configuration Path Source: https://knip.dev/overview/configuration Command-line usage to specify a custom configuration file path. ```bash knip --config path/to/knip.json ``` -------------------------------- ### Configure entry and project patterns Source: https://knip.dev/guides/handling-issues Define entry files or exclude specific directories from analysis using configuration patterns. ```json { "entry": ["src/index.ts", "src/models/*.ts"] } ``` ```json { "project": ["src/**/*.ts", "!**/__mocks__/**"] } ``` -------------------------------- ### Standardized Linter Annotations Source: https://knip.dev/explanations/why-use-knip Examples of common linter and formatter ignore comments that Knip avoids using in favor of standardized annotations. ```javascript // eslint-disable-next-line // prettier-ignore // @ts-expect-error ``` -------------------------------- ### Dependency issues shortcut Source: https://knip.dev/reference/cli Shortcut to report all dependency-related issues. ```bash --include dependencies,unlisted,binaries,unresolved,catalog ``` -------------------------------- ### Configure Workspaces Source: https://knip.dev/reference/configuration Define entry and project patterns for the root and individual workspace directories. ```json { "workspaces": { ".": { "entry": ["scripts/*.ts"], "project": ["scripts/**/*.ts"] }, "packages/*": { "entry": ["src/index.ts"], "project": ["src/**/*.ts"] } } } ``` -------------------------------- ### Run Knip in Basic Project Source: https://knip.dev/playground Executes the Knip command in the basic playground environment to identify unused files, unlisted dependencies, and unused exports. ```bash $ npm run knip Unused files (1) clutter.ts Unlisted dependencies (1) lodash util.ts Unused exports (1) unusedFunction unknown util.ts:6:14 ``` -------------------------------- ### Workspace filter formats Source: https://knip.dev/features/monorepos-and-workspaces Examples of various formats supported by the --workspace flag, including package names, globs, and directory paths. ```bash knip --workspace @myorg/my-lib # Package name knip --workspace '@myorg/*' # Package name glob knip --workspace packages/my-lib # Directory path knip --workspace './apps/*' # Directory glob ``` -------------------------------- ### Run Preprocessor via CLI Source: https://knip.dev/features/reporters Command line usage to apply a preprocessor file during Knip execution. ```bash knip --preprocessor ./preprocess.ts ``` -------------------------------- ### Run Knip with performance metrics Source: https://knip.dev/guides/performance Use the performance flag to view execution time and function invocation counts. ```bash knip --performance ``` -------------------------------- ### Execute Custom Reporter Source: https://knip.dev/features/reporters Run the Knip analysis using a local reporter file via the command line. ```bash knip --reporter ./my-reporter.ts ``` -------------------------------- ### Configure reporter options Source: https://knip.dev/reference/cli Pass additional configuration to a reporter as a JSON string. ```bash knip --reporter codeowners --reporter-options '{"path":".github/CODEOWNERS"}' ``` -------------------------------- ### Run Knip with a specific reporter Source: https://knip.dev/features/reporters Use the --reporter flag to specify the desired output format. ```bash knip --reporter compact ``` -------------------------------- ### Run Knip Performance Analysis Source: https://knip.dev/blog/slim-down-to-speed-up Execute the Knip CLI with the --performance flag to generate detailed timing and memory usage statistics. ```bash $ knip --performance Name size min max median sum ----------------------------- ---- ------ ------- ------- ------- findReferences 223 0.55 2252.35 8.46 5826.95 createProgram 2 50.78 1959.92 1005.35 2010.70 getTypeChecker 2 5.04 667.45 336.24 672.48 getImportsAndExports 396 0.00 7.19 0.11 104.46 Total running time: 9.7s (mem: 1487.39MB) ``` ```bash $ knip --performance ... Name size min max median sum ----------------------------- ---- ------ ------- ------- ------- createProgram 2 54.36 2138.45 1096.40 2192.81 getTypeChecker 2 7.40 664.83 336.12 672.23 getImportsAndExports 396 0.00 36.36 0.16 224.37 getSymbolAtLocation 2915 0.00 29.71 0.00 65.63 Total running time: 4.3s (mem: 729.67MB) ``` -------------------------------- ### Configure error handling for hints Source: https://knip.dev/reference/configuration Set configuration or tag hints to trigger a non-zero exit code. ```json { "treatConfigHintsAsErrors": true } ``` ```json { "treatTagHintsAsErrors": true } ``` -------------------------------- ### Compare unimported and Knip commands Source: https://knip.dev/explanations/comparison-and-migration Equivalent command for production-mode dependency and file analysis. ```bash unimported knip --production --dependencies --files ``` -------------------------------- ### Configure monorepo workspace package.json Source: https://knip.dev/features/source-mapping Define the main entry point for a workspace within a monorepo. ```json { "name": "@org/shared", "main": "dist/index.js" } ``` -------------------------------- ### Handle missing package entry file Source: https://knip.dev/reference/configuration-hints Message for when a package entry file cannot be located. ```text Package entry file not found ``` -------------------------------- ### Compare depcheck and Knip commands Source: https://knip.dev/explanations/comparison-and-migration Equivalent command for analyzing dependencies. ```bash depcheck knip --dependencies ``` -------------------------------- ### Configure Production Patterns Source: https://knip.dev/features/production-mode Use an exclamation mark suffix on patterns in the configuration file to designate them as production code. ```json { "entry": ["src/index.ts!", "build/script.js"], "project": ["src/**/*.ts!", "build/*.js"] } ``` -------------------------------- ### Reference a configuration file with toConfig Source: https://knip.dev/writing-a-plugin/inputs Use toConfig to reference a configuration file that should be handled by a different plugin. ```javascript toConfig('typescript', './path/to/tsconfig.json'); ``` -------------------------------- ### Configure ESLint and Cypress Plugins Source: https://knip.dev/features/integrated-monorepos Specify configuration and entry file patterns for plugins to prevent false positives for unused dependencies in application-specific configurations. ```json { "eslint": { "config": ["{apps,libs}/**/.eslintrc.json"] }, "cypress": { "entry": ["apps/**/cypress.config.ts", "apps/**/cypress/e2e/*.spec.ts"] } } ``` -------------------------------- ### Default release-it configuration Source: https://knip.dev/reference/plugins/release-it The default configuration paths used by the plugin to locate release-it settings. ```json { "release-it": { "config": [ ".release-it.{json,js,cjs,ts,yml,yaml,toml}", "package.json" ] } } ``` -------------------------------- ### Configure tsconfig.json for source mapping Source: https://knip.dev/features/source-mapping Set baseUrl and outDir in tsconfig.json to enable Knip to resolve build artifacts to source files. ```json { "compilerOptions": { "baseUrl": "src", "outDir": "dist" } } ``` -------------------------------- ### Define custom plugin configuration paths Source: https://knip.dev/explanations/plugins Use this configuration to point Knip to non-standard plugin configuration files. Supports both explicit array notation and shorthand string patterns. ```json { "playwright": { "config": ["e2e/playwright.config.ts"] }, "vite": "packages/*/vite.config.ts" // shorthand without `config` and array notation } ``` -------------------------------- ### Configure workspace entry and project patterns Source: https://knip.dev/features/monorepos-and-workspaces Define custom entry and project patterns for specific workspaces within the Knip configuration object. ```json { "workspaces": { ".": { "entry": "scripts/*.js", "project": "scripts/**/*.js" }, "packages/*": { "entry": "{index,cli}.ts", "project": "**/*.ts" }, "packages/cli": { "entry": "bin/cli.js" } } } ``` -------------------------------- ### Configure Knip to Include Namespace Exports Source: https://knip.dev/guides/namespace-imports Configuration to disable the default heuristic and enforce individual export tracking. ```json { "include": ["nsExports"] } ``` -------------------------------- ### Reference catalog entries in package.json Source: https://knip.dev/features/catalogs Use the catalog: protocol to reference dependencies defined in your catalog files. ```json { "dependencies": { "react": "catalog:", "zod": "catalog:validation" } } ``` -------------------------------- ### Define Default Entry and Project Patterns Source: https://knip.dev/explanations/entry-files The default configuration used by Knip to identify entry points and project files. Note that custom settings in the configuration file will override these defaults entirely. ```json { "entry": [ "{index,cli,main}.{js,cjs,mjs,jsx,ts,cts,mts,tsx}", "src/{index,cli,main}.{js,cjs,mjs,jsx,ts,cts,mts,tsx}" ], "project": ["**/*.{js,cjs,mjs,jsx,ts,cts,mts,tsx}!"] } ``` -------------------------------- ### Configure Entry Patterns with Negation Source: https://knip.dev/guides/configuring-project-files Use negated patterns to exclude specific files from being treated as entry points. ```json { "entry": ["src/routes/*.ts", "!src/routes/_*.ts"] } ``` -------------------------------- ### Define plugin binaries Source: https://knip.dev/writing-a-plugin/argument-parsing Specify the executables associated with the dependency. ```javascript { binaries: ['tsc']; } ``` -------------------------------- ### Define dynamic configuration with functions Source: https://knip.dev/reference/dynamic-configuration Export an async or regular function to return the configuration object dynamically. ```typescript import type { KnipConfig } from 'knip'; const config = async (): Promise => { const items = await fetchRepoInfo(); return { entry: ['src/index.ts', ...items], project: ['src/**/*.ts'], }; }; export default config; ``` ```javascript const config = async () => ({ entry: ['src/index.ts'], project: ['src/**/*.ts'], }); export default config; ``` -------------------------------- ### Define dynamic configuration with objects Source: https://knip.dev/reference/dynamic-configuration Use a TypeScript or JavaScript file to export a configuration object with type support. ```typescript import type { KnipConfig } from 'knip'; const config: KnipConfig = { entry: ['src/index.ts'], project: ['src/**/*.ts'], }; export default config; ``` ```javascript /** @type {import('knip').KnipConfig} */ const config = { entry: ['src/index.ts'], project: ['src/**/*.ts'], }; export default config; ``` -------------------------------- ### Usage Source: https://knip.dev/features/reporters How to invoke custom or external reporters via the CLI. ```APIDOC ## CLI Usage ### Description Use the `--reporter` argument to specify a local file or an external package. Multiple reporters can be used by repeating the argument. ### Command `knip --reporter [path-to-file-or-pkg-name]` ### Examples - Local: `knip --reporter ./my-reporter.ts` - External: `knip --reporter my-reporter-package` ``` -------------------------------- ### Nx binary argument parsing Source: https://knip.dev/reference/plugins/nx Configuration for parsing arguments from the Nx binary. ```javascript fromArgs: (parsed ) => (parsed._[0] === 'exec' ? [...parsed._.slice(1), ...(parsed['--'] ?? [])] : []) ``` -------------------------------- ### Prisma Shell Command Configuration Source: https://knip.dev/reference/plugins/prisma Custom configuration for parsing Prisma binary arguments and resolving schema inputs. ```javascript config: true resolveInputs: (parsed , { cwd }) => { const inputs = []; if (typeof parsed['schema'] === 'string') { inputs.push(resolveSchema(parsed['schema'], cwd)); } return inputs; } ``` -------------------------------- ### Define Project Files Source: https://knip.dev/reference/configuration Specify an array of glob patterns to identify all project files for analysis. ```json { "project": ["src/**/*.ts", "scripts/**/*.ts"] } ``` -------------------------------- ### Run Knip with auto-fix Source: https://knip.dev/features/auto-fix Basic command to apply automatic fixes for unused exports and dependencies. ```bash knip --fix ``` -------------------------------- ### Analyze Performance Source: https://knip.dev/reference/cli Outputs a table containing the count and execution time of expensive internal functions. Note that this is not supported in Bun due to missing performance.timerify support. ```bash $ knip --performance ``` -------------------------------- ### Enable a built-in compiler manually Source: https://knip.dev/features/compilers Set a compiler extension to true in the configuration to force its activation. ```javascript export default { compilers: { mdx: true, }, }; ``` -------------------------------- ### Run Knip in Production Mode Source: https://knip.dev/features/production-mode Execute Knip with the production flag to analyze only the designated production files. ```bash knip --production ``` -------------------------------- ### Configure rules in JSON Source: https://knip.dev/features/rules-and-filters Define rules in the configuration file to set issue severity levels. 'warn' prints issues in a faded color without counting towards the total error count, while 'off' excludes them entirely. ```json { "rules": { "files": "warn", "duplicates": "off" } } ``` -------------------------------- ### Inject path alias support Source: https://knip.dev/reference/known-issues Use environment options to enable path alias resolution for configuration files. ```bash NODE_OPTIONS="--import tsx" knip ``` ```bash NODE_OPTIONS="--import tsconfig-paths/register.js" knip ``` -------------------------------- ### Configure GitHub Actions for Knip Source: https://knip.dev/guides/using-knip-in-ci A standard workflow configuration to run Knip within a GitHub Actions environment. ```yaml name: Lint project on: push jobs: lint: runs-on: ubuntu-latest name: Ubuntu/Node v24 steps: - uses: actions/checkout@v6 - uses: actions/setup-node@v6 with: node-version: 24 - name: Install dependencies run: npm install --ignore-scripts - name: Run knip run: npm run knip ``` -------------------------------- ### Namespace Import Usage Source: https://knip.dev/guides/namespace-imports Demonstrates importing all exports as a namespace object and passing it to a function. ```javascript import * as NS from './my-namespace.js'; import send from 'stats'; send(NS); ``` -------------------------------- ### Default Serverless Framework Configuration Source: https://knip.dev/reference/plugins/serverless-framework The default configuration used by the plugin to identify serverless configuration files. ```json { "serverless-framework": { "config": [ "serverless.{js,cjs,mjs,ts,cts,mts,yml,yaml}" ] } } ``` -------------------------------- ### Default plugin configuration Source: https://knip.dev/reference/plugins/laravel-vite-plugin The default configuration applied when the plugin is detected in package.json. ```json { "laravel-vite-plugin": { "config": [ "vite.config.{js,mjs,ts,cjs,mts,cts}" ] } } ``` -------------------------------- ### Next.js Shell Command Configuration Source: https://knip.dev/reference/plugins/next Configuration for parsing arguments for the next binary, including boolean flags and input resolution logic. ```javascript boolean: ["turbo", "turbopack"] resolveInputs: parsed => { const dir = commands.has(parsed._[0]) ? parsed._[1] : undefined; if (!dir) return []; return [toConfig('next', join(dir, 'next.config'))]; } ``` -------------------------------- ### Update dependencies after fix Source: https://knip.dev/features/auto-fix Commands to synchronize package.json changes with the local environment. ```bash npm install ``` ```bash pnpm install ``` ```bash bun install ``` ```bash yarn ``` -------------------------------- ### Handle stale workspace configuration Source: https://knip.dev/reference/configuration-hints Message for when a workspace key no longer matches an existing directory. ```text Remove from workspaces ``` -------------------------------- ### Circular dependency issues shortcut Source: https://knip.dev/reference/cli Shortcut to report only circular dependencies. ```bash --include cycles ``` -------------------------------- ### Shell command configuration Source: https://knip.dev/reference/plugins/dependency-cruiser Configuration setting to enable argument parsing for dependency-cruiser binaries. ```yaml config: true ```