使用npm link 创建本地模块
1. npm link 介绍
创建一个全局的符号链接,优点是方便我们进行本地node模块的开发调用,和后期发布私服,或者npm 仓库调用是一致的
以下为官方的说明:
First, npm link in a package folder 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. (see npm-config for the value of prefix). It will
also link any bins in the package to {prefix}/bin/{name}.
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.
Note that package-name is taken from package.json, not from directory name.
2. 简单例子
a.创建目录
mkdir userlogin usermodule
b.初始化项目
cd usermodule
yarn init -y
yarn add shortid
touch index.js
const shortid = require("shortid");
module.exports={
name:"dalong",
age:33,
id:shortid.generate()
}
package.json
{
"name": "usermodule",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"shortid": "^2.2.8"
}
}
cd userlogin
yarn init -y
touch app.js
const usermodule =require("usermodule");
console.log(usermodule)
package.json
{
"name": "userlogin",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"shortid": "^1.0.0"
},
"scripts": {
"run":"node app"
}
}
项目结构如下:
├── userlogin
│ ├── app.js
│ └── package.json
└── usermodule
├── index.js
├── package.json
└── yarn.lock
3. 运行代码
一般来说没有发布的模块我们是没法直接使用的,比如上面的代码,我们直接运行会有错误
yarn run run
yarn run v1.3.2
$ node app
module.js:538
throw err;
^
Error: Cannot find module 'usermodule'
at Function.Module._resolveFilename (module.js:536:15)
at Function.Module._load (module.js:466:25)
at Module.require (module.js:579:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/Users/dalong/mylearning/nodelinkdemo/userlogin/app.js:1:81)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
具体的解决方法:
* 发布到私有或者官方仓库
* 使用npm link
以下指演示使用link 的方法
在 usermodule 的目录外边执行 npm link usermodule(此名称为package的名称,不是目录的名称)
再次进入 userlogin 执行 yarn run run
结果如下:
yarn run v1.3.2
$ node app
{ name: 'dalong', age: 33, id: 'SkZN0OjYG' }
4. 参考资料
https://docs.npmjs.com/cli/link
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)