如何在本地测试NPM软件包

如果要开发自己的npm软件包,则首先必须在本地对其进行测试。

我对一个我想模块化的项目有这种需求。

我有一个叫我的包裹,例如flaviocopes-common-database

我以为前提flaviocopes-给它一个唯一的命名空间。

在包装内,我添加了一个package.json文件中带有模块名称的文件name属性和一些依赖项:

{
  "name": "flaviocopes-common-database",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "pg": "^8.0.2",
    "sequelize": "^5.21.6"
  }
}

然后我跑了

npm link

This created a symbolic link in the /usr/local/lib/node_modules/ folder, that contains the global npm packages in the system, the ones installed using npm -g, to be clear.

I had

/usr/local/lib/node_modules/flaviocopes-common-database

Pointing to the local file I had in

/Users/flavio/dev/code/flaviocopes-common-database

Now in another project I wanted to use this module, so I ran

npm link flaviocopes-common-database

and I was able to import it in the Node.js code using the usual require() syntax:

const database = require('flaviocopes-common-database')

Download my free Node.js Handbook


More node tutorials: