目标1:搭建 test-cli 脚手架
目标2:脚手架本地调试
一、搭建 test-cli 脚手架
操作步骤如下:
step1: 初始化操作
// 创建test目录
mkdir test
// 进入test目录
cd test
// 创建 package.json
// "name"为 "test",
npm init -y
// 用编辑器vscode打开项目
code .
构建下图所示的目录结构
step2: 编写bin\index.js文件内容,该文件便是我们的脚手架入口文件
内容如下:
// 头部(必须)
#!/usr/bin/env node
// 相关逻辑代码
console.log(process)
// ......其他代码内容1....
// ......其他代码内容2....
step3:修改package.json文件
添加bin字段
"bin": {
"test": "bin/index.js"
},
step4:发布项目到npm
// 登录npm
npm login
// 发布
npm publish
step5:使用我们发布成功的包
// 全局安装发布的包
npm i test -g
// 命令行执行
test
至此,脚手架项目模板搭建完成。
二、脚手架本地调试
1、npm link 介绍
参考链接:https://docs.npmjs.com/cli/v9/commands/npm-link/
npm link [<package-spec>]
alias: ln
This is handy for installing your own stuff, so that you can work on it and test iteratively without having to continually rebuild.
Package linking is a two-step process.
First, npm link
in a package folder with no arguments will create a symlink in the global folder {prefix}/lib/node_modules/<package>
that links to the package where the npm link
command was executed. It will also link any bins in the package to {prefix}/bin/{name}
. Note that npm link
uses the global prefix (see npm prefix -g
for its value).
1、npm link:
在全局npm的 node_modules下生成一个软链接,同时也会在npm目录下生成对应的脚本文件
Next, in some other location, npm link package-name
will create a symbolic link from globally-installed package-name
to node_modules/
of the current folder.
2、npm link test-lib(你的库文件包名):
运行该命令后,会在当前项目test的node_modules下生成test-lib的软连接。
如下图
这样,你就可以在不用发布test-lib的情况下,使用test-lib进行调试啦。
// 将test-lib链接到全局npm目录
cd test-lib
npm link
Note that package-name
is taken from package.json
, not from the directory name.
注意:
1,如果需要解除link,可以使用 npm unlink
2, 使用npm link,重点关注的位置:
1)全局npm的安装位置 (可以通过npm prefix -g 查看) 2)全局npm 目录下的脚本文件, 3)全局npm 目录下的node_modules中的软链接:C:\Users\DELL\AppData\Roaming\npm\test
2、只存在一个项目
test项目包名为: test
// step1:
cd test
npm link
// step2:
test // 执行test命令
3、存在多个项目,需要分包处理时
- 当前项目 : test
- test 想要链接使用的 库:test-lib
// step1: 将test-lib链接到test项目的node_modules
cd test
npm link test-lib
// step2: 修改 test 目录下的 package.json,手动添加以下依赖(正式使用时必须添加)
"dependencies": {
"test-lib": "^1.1.0"
}
// step3:如果入口文件是”lib\index.js“,需要修改库test-lib项目的main 字段,
// 原始默认入口是 “index.js”
"main": "lib/index.js",
暂无评论内容