使用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
 
原文地址:https://www.cnblogs.com/rongfengliang/p/8595278.html