Logotipo de Fix Knip Unused Exports

Fix Knip Unused Exports

Organización
Factory-AI
fix-knip-unused-exports

Fix knip "Unused exports" violations. Handles all violation categories: test-only exports (extract to new file), dead barrel re-exports (remove from index.ts), and internally-only-used exports (un-export). Use when `npm run knip` reports unused exports.

Descripción general

EditorFactory-AI
Repositoriofactory-plugins
Nombre de la habilidadfix-knip-unused-exports
Estrellas
111
Forks
15
Archivos incluidos
Solo instrucciones
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando la petición encaja con la habilidad.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • Todo en las instrucciones

    Todo lo que necesita el modelo está en las instrucciones: no hay archivos adicionales que sincronizar.

  • Código abierto

    Publicada por Factory-AI en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA Fix Knip Unused Exports en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/Factory-AI/factory-plugins/tree/master/plugins/typescript/skills/fix-knip-unused-exports
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Factory-AI/factory-plugins.git /tmp/factory-plugins
mkdir -p .claude/skills
cp -r /tmp/factory-plugins/plugins/typescript/skills/fix-knip-unused-exports .claude/skills/fix-knip-unused-exports
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Fix Knip Unused Exports en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición encaja con la habilidad, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga Fix Knip Unused Exports automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que Fix Knip Unused Exports no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición que encaja con la habilidad, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo seguirá.

Fix Knip Unused Exports

Fix knip "Unused exports" violations. There are several categories of violation, each with a different fix strategy.

When to Use

  • npm run knip reports "Unused exports"

When NOT to Use

  • The export is consumed by non-test production code in another file -- something else is wrong

Workflow

1. Identify Violations

bash
npm run knip

Output looks like:

Unused exports (3)
::error file=packages/foo/src/bar.ts,line=42,title=Unused exports::myFunction

2. Classify Each Violation

For each flagged export, grep the entire repository (not just the package):

bash
rg "myFunction"

Determine which category it falls into:

CategoryCallersFix
Test-only exportUsed in same file + test files onlyExtract to new file
Dead barrel re-exportRe-exported from index.ts, but production code imports via relative paths or other subpaths insteadRemove the re-export from the barrel
Internally-only-used exportUsed only within the same file, not by tests or other filesRemove the export keyword
Dead codeNo callers anywhereDelete the export
Production consumer existsUsed by non-test code in another fileNot a knip issue -- investigate further

Important: When grepping, exclude test files to identify production consumers:

bash
rg "myFunction" --glob '!**/*.test.*'

Fix: Test-Only Exports (Extract to New File)

When a function is exported solely for test access but is also used internally in the same file.

Plan the Extraction

Before writing code, answer these questions:

a) What moves to the new file?

  • The flagged export function/class/const
  • All private helper functions it depends on
  • All private constants/types it depends on

b) Are any helpers shared with functions staying behind?

  • If yes, the helper must be exported from the new file, and the original file imports it
  • This means the new file will have 2+ exports (which is fine for any filename-match-export lint rule)

c) Will the new file have exactly one exported function?

  • If your project enforces a filename-match-export lint rule, the file MUST be named after that export: myFunction.ts
  • If the file has 2+ function exports, the name is flexible

d) Does a test file with a matching name exist?

  • If bar.ts stays and bar.test.ts exists, the test must still import something from ./bar (if your project enforces a test-imports-source rule)
  • If bar.ts is deleted (everything moved out), that rule typically only applies when the matching source file exists

e) Any circular dependency risk?

  • Draw the import graph: new file -> original file -> new file is circular
  • Fix: move the shared dependency to the new file or a third file

f) Does it export a constant?

  • If your project enforces a constants-file-organization lint rule, exported constants must live in a file named constants.ts
  • If the extracted function depends on a constant that other functions in the original file also use, do NOT export the constant from the new file. Instead, call the function (e.g., replace BUDGET[effort] with getBudget(effort)) to avoid needing a separate constants.ts

Execute the Extraction

Create the new file in the same directory:

typescript
// myFunction.ts (new file)
import { SomeType } from '../types';

function privateHelper(): void { /* ... */ }

export function myFunction(): SomeType {
  return privateHelper();
}

Update the original file to import from the new file:

typescript
// bar.ts (original file, updated)
import { myFunction } from './myFunction';

function otherFunction() {
  const result = myFunction(); // Now imports from new file
}

Update test files to import from the new file:

typescript
// bar.test.ts (updated)
import { myFunction } from './myFunction';
// If bar.ts still exists, you may need to also import something from './bar'
// to satisfy any test-imports-source rule

Watch for Chained Violations

After extracting, run npm run knip again. If function A was extracted to a new file alongside function B that A calls, but B is also only consumed by tests externally, knip will flag B too. You need to extract B to its own file so that A's file creates a genuine production import of B.

Example: suppose throwMappedError was first extracted alongside mapResponseFailure into error-mappers.ts. If throwMappedError is only called internally within that file (by mapResponseFailure), it will still be flagged. Fix: extract it to throwMappedError.ts, making the import from error-mappers.ts a genuine production consumer.

Fix: Dead Barrel Re-Exports (Remove from index.ts)

When a barrel index.ts re-exports something, but no production code imports it through the barrel. This happens when:

  • Production code within the same package uses relative imports (e.g., import { x } from './source') instead of the barrel
  • Production code in other packages imports directly from a subpath (e.g., @scope/pkg/feature/handlers) instead of the barrel
  • The re-export was added speculatively but never consumed

How to Identify

Grep excluding test files. If the only hits are:

  • The barrel index.ts itself
  • Source files using relative imports within the same package
  • Test files

Then the barrel re-export is unused. Simply remove it from index.ts.

Cross-Package Test Imports

If a test in another package imports the symbol through the barrel (e.g., import { x } from '@scope/pkg/feature'), you need to provide an alternative import path after removing the barrel re-export:

  1. Add a subpath export in the source package's package.json:

    json
    {
      "exports": {
        "./feature": "./src/feature/index.ts",
        "./feature/doSomething": "./src/feature/doSomething.ts"
      }
    }
  2. Update the test to import from the new subpath:

    typescript
    import { doSomething } from '@scope/pkg/feature/doSomething';

This pattern follows typical subpath-export conventions used in monorepos.

Fix: Internally-Only-Used Exports (Un-export)

When an export is only used within the same file and not imported by anything else (not even tests), just remove the export keyword:

typescript
// Before
export const MySchema = z.object({ ... });

// After
const MySchema = z.object({ ... });

This is common for Zod schemas that are only used as building blocks for other schemas in the same file.

Verify

Run ALL of these checks on the affected packages:

bash
# Knip passes (the whole point)
npm run knip

# Types still compile
npm run typecheck

# Tests still pass
npm run test

# Lint passes (catches filename-match-export, test-imports-source, constants-file-organization, etc.)
npm run lint

If cross-package imports exist, also verify the consuming package.

Interacting Lint Rules

Many TypeScript monorepos layer additional custom lint rules on top of knip. Adapt the fixes below to whichever of these your project uses.

filename-match-export (or similar)

If a file has exactly ONE exported function (not a React component), the filename must match the function name.

  • export function loadConfig in loadConfig.ts -- passes
  • export function loadConfig in helpers.ts -- fails
  • Two exports in helpers.ts -- rule does not apply (multiple exports)

test-imports-source (or similar)

If foo.test.ts and foo.ts both exist, the test must import from ./foo.

  • Imports like import { x } from './foo' satisfy the rule
  • Typically also accepts importing from '.' or './index' if index.ts re-exports from foo.ts
  • If foo.ts is deleted, the rule does not apply

constants-file-organization (or similar)

Exported constants must be defined in a file named constants.ts.

  • If you extract a function that depends on a shared constant, do NOT export the constant from the function's file
  • Instead, replace direct constant access with function calls (e.g., BUDGET[effort] becomes getBudget(effort))
  • Or move the constant to a constants.ts file

How Knip Traces Exports

  • Knip ignores test files (**/*.test.*, **/*.spec.*)
  • ignoreIssues in knip.json suppresses warnings ON the listed file, but does NOT make the source export "used"
  • Barrel re-exports (export { x } from './source') from an index.ts with ignoreIssues do NOT count as usage of the source export
  • Only genuine imports from non-test, non-ignored project files count as usage
  • includeEntryExports: true (if set) means exports from entry point files are checked too, so entry-point-style files (migrations, scripts) may need explicit ignoreIssues

Package Subpath Exports

When removing barrel re-exports that cross-package tests relied on, add subpath exports to package.json:

json
{
  "exports": {
    "./feature": "./src/feature/index.ts",
    "./feature/doSomething": "./src/feature/doSomething.ts"
  }
}

What Not to Do

  • Do not add files to ignoreIssues in knip.json unless they are genuine entry point scripts (migrations, CLIs)
  • Do not merge all functions into one file to reduce exports -- same-file usage of an export does not count as usage from knip's perspective
  • Do not remove the export keyword if tests need it -- the tests would break
  • Do not create circular imports between the new and original files
  • Do not export constants from non-constants.ts files if your project enforces a constants-file-organization lint rule

Preguntas frecuentes

¿Qué hace la habilidad de IA Fix Knip Unused Exports?

Fix knip "Unused exports" violations. Handles all violation categories: test-only exports (extract to new file), dead barrel re-exports (remove from index.ts), and internally-only-used exports (un-export). Use when `npm run knip` reports unused exports.

¿Por qué usar Fix Knip Unused Exports en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Fix Knip Unused Exports está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo Fix Knip Unused Exports en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/Factory-AI/factory-plugins/tree/master/plugins/typescript/skills/fix-knip-unused-exports. TypingMind lee el archivo SKILL.md de esa carpeta e instala su contenido como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Fix Knip Unused Exports?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar Fix Knip Unused Exports?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Fix Knip Unused Exports con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA Fix Knip Unused Exports?

Factory-AI la ha publicado en GitHub. Consulta el repositorio para conocer las condiciones de la licencia. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver el directorio

Crea ya tu propio espacio de trabajo con IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇