Plugin Development in Practice: From Your First Plugin to Publishing
This guide provides a practical roadmap for developing, building, and publishing a TypeScript-based plugin. It covers the core architecture of plugin frameworks, configuring `tsconfig.json` for ESM, troubleshooting common editor errors, validating build artifacts, and managing workspace dependencies across different package managers.
Target Audience and Prerequisites
This article is intended for developers who have a basic understanding of TypeScript and are comfortable using the terminal. The examples are based on Node.js 20 and above, TypeScript 5.6 and above, and npm workspaces. The PluginContext in the plugin contract is a placeholder type for demonstration purposes; in practice, refer to the plugin specifications of the framework you are using.
1. The Core Concept
A plugin-based framework typically consists of two components: a configuration tree and a loader responsible for loading plugins based on that configuration. A plugin itself comprises two parts: code and a declaration. The code implements the functionality, while the declaration describes where the plugin mounts and what it depends on.
When developing plugins, most issues can be categorized into four types:
- Type resolution (compile-time)
- Module resolution (runtime)
- Mount configuration
- Publish content
When troubleshooting, first identify which category the problem falls into, then verify each item using the corresponding command. This is the most efficient approach.
2. Building a Minimal Plugin from Scratch
First, create the following directory structure:
hello-plugin/├── package.json├── tsconfig.json├── patches/│ └── hello.patch.json└── src/└── index.ts
The package.json content should look like this:
{"name": "@demo/hello-plugin","version": "0.1.0","type": "module","types": "./dist/index.d.ts","exports": {".": {"types": "./dist/index.d.ts","development": "./src/index.ts","import": "./dist/index.js","default": "./dist/index.js"}},"files": ["dist", "patches"],"scripts": {"build": "tsc -p tsconfig.json","typecheck": "tsc --noEmit -p tsconfig.json"},"devDependencies": {"typescript": "^5.6.0"}}
The files field determines which files are included during publication. Here, only the build output and patches directories are included; the source code will not be published. The development condition only takes effect when explicitly enabled at runtime; a standard node command will not activate it automatically.
The src/index.ts content is as follows:
export interface PluginContext {log(message: string): void;}export default function createPlugin(ctx: PluginContext) {return {name: "hello-plugin",setup() {ctx.log("hello-plugin loaded");},};}
The patch file is used to mount the plugin into the configuration tree. The structure below illustrates the concept; the actual field names and mounting location should align with your framework’s documentation:
{"target": "tools","mount": {"id": "hello","entry": "@demo/hello-plugin"}}
3. Key Configurations in tsconfig.json
Here is the minimal tsconfig.json that pairs with the package.json above:
{"compilerOptions": {"target": "ES2022","module": "NodeNext","moduleResolution": "NodeNext","rootDir": "src","outDir": "dist","declaration": true,"strict": true,"esModuleInterop": true,"skipLibCheck": true},"include": ["src/**/*.ts"]}
The purpose of each option is as follows:
| Configuration | Value | Description |
|---|---|---|
module and moduleResolution |
Both NodeNext |
Works with "type": "module" to resolve package entry points according to Node.js rules. They must be set as a pair; otherwise, the compiler may fail to find paths declared in exports. |
rootDir |
src |
Fixes the source root directory, ensuring the directory structure in dist matches the source. |
outDir |
dist |
The output location for compiled artifacts, corresponding to the exports field in package.json. |
declaration |
true |
Generates .d.ts files, allowing other plugins to obtain type information. |
paths |
Not used here | Path aliases only affect compile-time checks. tsc does not rewrite paths in the build output. To use aliases at runtime, you need a bundler or should switch to relative paths. |
composite and incremental |
For multi-package setups | Used with project references for incremental builds. Not required for single-package projects. |
In NodeNext mode, relative imports in the source code must include explicit file extensions. For example, import { x } from "./util" will throw an error and should be changed to ./util.js. This is a common reason why developers see red squiggly lines in their editors.
To verify whether paths aliases remain in the build output, you can run:
grep -rn 'from "@/' dist/
If the output is empty, no untransformed aliases exist.
4. Troubleshooting Editor Errors
Red squiggly lines in editors usually stem from the compiler’s type resolution rather than runtime errors. The table below lists common symptoms and inspection methods.
| Symptom | Possible Cause | Check Command or Method |
|---|---|---|
Cannot find module '...' or its corresponding type declarations |
Mismatch between moduleResolution and module, or missing types condition in dependency exports |
Run npx tsc --showConfig to view the final effective configuration |
TS2835: Relative import paths need explicit file extensions |
Missing .js extension in relative imports under NodeNext |
Append .js to the end of the import statement |
| Editor jumps to remote package types instead of local workspace | Dependency is not linked to the workspace; remote version is installed | Run npm ls @demo/hello-plugin. If it shows -> ./packages/..., it is linked |
Cannot find name 'X', where X comes from a framework type package |
Type package not installed, or not declared in types |
Verify node_modules/<framework-type-package> exists, and check the types field in tsconfig |
When troubleshooting, it is recommended to run npm run typecheck in the terminal first. If the command line shows no errors but the editor still displays red lines, it is usually an editor cache issue; restarting the TypeScript server will fix it. If the command line also reports errors, the problem lies in the project configuration and should be checked item by item according to the table above.
5. Build Process and Artifact Checkpoints
The essence of building is compiling src into dist while generating declaration files. The following table outlines the command, expected artifacts, and checkpoints for each step.
| Step | Command | Expected Artifact | Checkpoint |
|---|---|---|---|
| Type check | npm run typecheck |
No output file | Exit code is 0 |
| Compile | npm run build |
dist/index.js, dist/index.d.ts |
Both files exist |
| Artifact verification | node --input-type=module -e "import('@demo/hello-plugin').then(m => console.log(typeof m.default))" |
Outputs function |
Package name resolves to dist via self-referencing |
In a multi-package workspace, build order is crucial. If a dependency package has not generated its .d.ts files first, packages relying on it will fail type checking. Using tsc -b with project references allows automatic building in dependency order. If you only use standard build commands, you must manually sort by dependency relationship and rebuild the dependency packages after each change.
When cleaning old artifacts, only delete the dist directory within the project and ensure you are in the correct path first:
pwdrm -rf dist && npm run build
6. Source Mode vs. Artifact Mode
Plugins typically support two runtime modes. The differences are as follows:
| Comparison | Source Mode | Artifact Mode |
|---|---|---|
| Startup method | Directly run TypeScript using tools like tsx src/index.ts |
Run compiled JavaScript using node dist/index.js |
| Startup speed | Slower, due to runtime transpilation | Faster |
| Use case | Local debugging, immediate effect after changes | Production environment and pre-release verification |
| Prerequisites | Install transpilation tools and ensure the development condition in exports is enabled |
Run npm run build first |
| Common risks | Source mode passes but artifact mode fails, usually because the build was not updated | Forgetting to rebuild, running stale code |
Switching between the two modes is achieved via exports conditions. During development, enable the development condition to point to the source code; in production, use the import or default condition to point to the artifacts. If the behavior is inconsistent between the two modes, clean the artifacts, rebuild, and then compare the results.
7. Workspace Dependencies and Linking Mechanism
Workspaces are used to manage multiple local packages collectively. npm workspaces creates a symbolic link in the root directory’s node_modules/@scope/, pointing to the local package directory. Therefore, after modifying a local package, dependent packages can immediately read the new code—provided the modified package has been rebuilt.
Different package managers handle local dependency syntax differently:
| Package Manager | Local Dependency Syntax | Handling During Publish |
|---|---|---|
| npm workspaces | Use version ranges directly, e.g., "^0.1.0"; linking is handled automatically by npm |
Version range published as-is |
| pnpm | Use "workspace:*" or "workspace:^" |
pnpm publish replaces it with the specific version number |
| Yarn Berry | Use "workspace:^" |
yarn npm publish replaces it with the specific version number |
One critical point to note: regardless of the package manager, always verify the final package.json and lockfiles before publishing to ensure all workspace dependencies have been correctly resolved to their intended published versions.
