typescript自定义npm命令行工具

126 阅读1分钟

1.初始化 NPM 包

如果你在windows,直接在需要开发的目录创建一个项目,使用vscode等工具Terminal内键入以下命令初始化,初始化后会生成package.json文件。

npm init 或者使用, npm init -y 跳过所有提问

package.json文件

{
  "name": "qy_terminal",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "tsc -b",
    "watch": "tsc -w"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "typescript": "^5.5.3"
  },
  "bin": {
    "qy": "./dist/index.js"
  }
}

2.使用 npm 安装Typescript

npm i typescript -D

3.使用当前项目中的 typescript依赖包来生成tsconfig.json 文件

./node_modules/.bin/tsc --init

tsconfig.json修改成如下:

{
  "compilerOptions": {
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    "module": "commonjs",                                /* Specify what module code is generated. */
    "rootDir": "./src",                                  /* Specify the root folder within your source files. */
    "moduleResolution": "node",                     /* Specify how TypeScript looks up a file from a given module specifier. */
    "resolveJsonModule": true,                        /* Enable importing .json files. */
    "outDir": "./dist",                                   /* Specify an output folder for all emitted files. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */
    "strict": true,                                      /* Enable all strict type-checking options. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  }
}

4.在src文件夹新建一个index.ts文件

在项目目录运行npm run watch这样可以监控src中的ts文件自动编译到dist文件夹中。

在index.ts文件的第一行添加 #!/usr/bin/env node这行不可少

然后在第二行输入console.log("hello qy");并保存

5.在package文件中添加一个bin字段,bin字段是一个键值对,键名是生成的.cmd文件的名字,值是执行这个命名所要执行的脚本.

"bin":{
    "qy":"./dist/index.js"
}

6.打开终端进入当前项目的根路径,执行npm linknode会自动去全局路径创建cmd文

7.完成上面步骤后,我们就可以在电脑什么目录使用了该工具了

用法:在控制台输入qy就可以输出hello qy了