下面是一个完整的指南,介绍如何使用 TypeScript 或 JavaScript 创建自己的 npm 插件并发布到 npm 仓库。
1. 初始化项目
首先创建一个新目录并初始化 npm 项目:
mkdir my-plugin
cd my-plugin
npm init -y
这会生成一个 package.json
文件。
2. 项目结构
一个典型的 npm 插件项目结构如下:
my-plugin/
├── src/ # 源代码目录
│ └── index.ts # 主入口文件
├── dist/ # 编译后的输出目录
├── tests/ # 测试文件
├── .gitignore # Git 忽略文件
├── package.json # 项目配置文件
├── tsconfig.json # TypeScript 配置 (如果使用 TS)
└── README.md # 项目文档
3. 添加 TypeScript 支持 (可选)
如果你使用 TypeScript:
npm install typescript @types/node --save-dev
创建 tsconfig.json
:
{
"compilerOptions": {
"target": "ES6",
"module": "CommonJS",
"declaration": true,
"outDir": "./dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
4. 编写插件代码
在 src/index.ts
中编写你的插件代码:
class MyPlugin {
private options: any;
constructor(options: any = {}) {
this.options = options;
}
greet(name: string = 'World'): string {
return `Hello, ${name}!`;
}
configure(newOptions: any): void {
this.options = { ...this.options, ...newOptions };
}
}
export default MyPlugin;
如果是纯 JavaScript 版本 (src/index.js
):
class MyPlugin {
constructor(options = {}) {
this.options = options;
}
greet(name = 'World') {
return `Hello, ${name}!`;
}
configure(newOptions) {
this.options = { ...this.options, ...newOptions };
}
}
module.exports = MyPlugin;
5. 配置 package.json
更新 package.json
中的重要字段:
{
"name": "my-plugin",
"version": "1.0.0",
"description": "A simple npm plugin",
"main": "dist/index.js",
"types": "dist/index.d.ts", // 仅TypeScript需要
"scripts": {
"build": "tsc", // TypeScript使用
// "build": "babel src -d dist", // JavaScript使用Babel时
"prepublish": "npm run build",
"test": "jest"
},
"keywords": ["plugin", "demo"],
"author": "Your Name",
"license": "MIT",
"devDependencies": {
"typescript": "^4.0.0"
}
}
6. 添加构建和测试脚本
对于 TypeScript 项目,build
脚本已经在上面配置。对于 JavaScript 项目,你可能需要使用 Babel 进行转译:
npm install @babel/core @babel/cli @babel/preset-env --save-dev
创建 .babelrc
文件:
{
"presets": ["@babel/preset-env"]
}
7. 本地测试
在发布前,你可以在本地测试你的插件:
构建你的插件:
npm run build
使用
npm link
在本地测试:npm link
在另一个项目中测试:
cd ../some-test-project npm link my-plugin
然后在测试项目中:
const MyPlugin = require('my-plugin'); const plugin = new MyPlugin(); console.log(plugin.greet('Developer'));
8. 发布到 npm
首先注册一个 npm 账号 (如果还没有):
npm adduser
登录:
npm login
确保版本号正确 (遵循语义化版本控制):
- 主版本号 (MAJOR): 不兼容的 API 修改
- 次版本号 (MINOR): 向下兼容的功能新增
- 修订号 (PATCH): 向下兼容的问题修正
更新版本号:
npm version patch # 或 minor, major
发布:
npm publish
如果是公共包,不需要额外参数。如果是私有包,需要付费账户或在
package.json
中添加"private": true
。
9. 更新插件
当你需要更新插件时:
- 修改代码
- 更新版本号:
npm version patch # 或其他合适的版本号
- 重新发布:
npm publish
10. 最佳实践
- 完善的文档: 在 README.md 中详细说明插件的使用方法、API 和示例
- 单元测试: 使用 Jest 或 Mocha 添加测试
- 持续集成: 配置 GitHub Actions 或 Travis CI
- 代码质量: 使用 ESLint 和 Prettier 保持代码风格一致
- 类型定义: 即使使用 JavaScript,也可以添加 JSDoc 或创建
.d.ts
文件
完整示例
这里是一个简单的 TypeScript npm 插件完整示例:
src/index.ts
:
interface PluginOptions {
prefix?: string;
suffix?: string;
}
/**
* MyPlugin - A simple demonstration plugin
*/
class MyPlugin {
private options: PluginOptions;
constructor(options: PluginOptions = {}) {
this.options = {
prefix: options.prefix || '',
suffix: options.suffix || ''
};
}
/**
* Generates a greeting message
* @param name Name to greet
* @returns Greeting message
*/
greet(name: string = 'World'): string {
return `${this.options.prefix}Hello, ${name}!${this.options.suffix}`;
}
/**
* Updates plugin configuration
* @param newOptions New options to merge
*/
configure(newOptions: PluginOptions): void {
this.options = { ...this.options, ...newOptions };
}
}
export default MyPlugin;
package.json
:
{
"name": "my-awesome-plugin",
"version": "1.0.0",
"description": "A simple demonstration npm plugin",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc",
"test": "jest",
"prepublish": "npm run build"
},
"keywords": [
"plugin",
"demo",
"example"
],
"author": "Your Name <your.email@example.com>",
"license": "MIT",
"devDependencies": {
"@types/jest": "^27.0.2",
"jest": "^27.2.5",
"ts-jest": "^27.0.5",
"typescript": "^4.4.3"
}
}
tsconfig.json
:
{
"compilerOptions": {
"target": "ES6",
"module": "CommonJS",
"declaration": true,
"outDir": "./dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.test.ts"]
}
README.md
:
# My Awesome Plugin
A simple demonstration npm plugin written in TypeScript.
## Installation
```bash
npm install my-awesome-plugin
```
## Usage
```javascript
import MyPlugin from 'my-awesome-plugin';
const plugin = new MyPlugin({ prefix: '[', suffix: ']' });
console.log(plugin.greet('World')); // Output: "[Hello, World!]"
plugin.configure({ prefix: '' });
console.log(plugin.greet('Developer')); // Output: "Hello, Developer!]"
```
## API
### `new MyPlugin(options?: PluginOptions)`
Creates a new plugin instance.
#### Options
- `prefix?: string` - Text to prepend to the greeting
- `suffix?: string` - Text to append to the greeting
### `greet(name?: string): string`
Generates a greeting message.
### `configure(newOptions: PluginOptions): void`
Updates plugin configuration.
通过以上步骤,你就可以创建、测试并发布自己的 npm 插件了