【前端】手把手教你用TypeScript写一个简单的eslint插件并发布到npm
以下是一个简化的例子,展示如何用TypeScript编写一个ESLint插件,并发布到npm:
- 初始化npm项目并安装依赖:
mkdir my-eslint-plugin
cd my-eslint-plugin
npm init -y
npm install eslint @types/estree --save-dev
npm install typescript ts-node eslint-plugin-test --save-dev
- 创建
tsconfig.json
:
{
"compilerOptions": {
"module": "commonjs",
"target": "es2017",
"noImplicitReturns": true,
"strictNullChecks": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"types": ["estree"],
"outDir": "dist"
},
"include": ["src/**/*.ts"]
}
- 创建
src/index.ts
并编写ESLint插件:
import { AST, ASTNode, ASTPlugin, ASTPluginFactory } from "eslint-plugin-test";
class MyPlugin implements ASTPlugin {
setup(info: any): void {
// 插件设置逻辑
}
apply(node: ASTNode, info: any): void {
// 检查node并报告问题逻辑
}
}
const factory: ASTPluginFactory = (context: any) => {
return {
name: "my-plugin",
enter(node: ASTNode) {
const plugin = new MyPlugin();
plugin.setup(context);
plugin.apply(node, context);
}
};
};
export = factory;
- 创建
src/rules/no-unused-variables.ts
并编写规则:
import { AST, ASTNode, ASTPlugin, ASTPluginFactory } from "eslint-plugin-test";
class NoUnusedVariables implements ASTPlugin {
setup(info: any): void {
// 设置逻辑
}
apply(node: ASTNode, info: any): void {
// 检查并报告未使用的变量
}
}
const factory: ASTPluginFactory = (context: any) => {
return {
name: "no-unused-variables",
enter(node: ASTNode) {
const plugin = new NoUnusedVariables();
plugin.setup(context);
plugin.apply(node, context);
}
};
};
export = factory;
- 编写
package.json
中的main
字段指向入口文件:
{
"name": "my-eslint-plugin",
"version": "1.0.0",
"main": "dist/index.js",
"scripts": {
"build": "tsc",
"lint": "tslint --project ."
},
"devDependencies": {
"eslint-plugin-test": "^1.0.0",
"tslint": "^5.10.0",
"typescript": "^2.9.2"
},
"peerDependencies": {
"eslint": "^4.0.0",
"@types/estree": "^0.0.46"
},
"keywords": ["eslint-plugin"],
"author": "Your Name",
"license": "MIT"
}
- 编译并测试插件:
npm run build
发布到npm:
确保你已在npm官网注册账号,并且在本地设置了npm的配置。
npm login
npm publish
以上步骤创建了一个简单的ESLint插件,并展示了如何将其编译并发布到npm。这个例子提供了一个框架,开发者可以在此基础上添加自
评论已关闭