简体   繁体   English

NPM模块-如何利用package.json文件?

[英]NPM Module - How to leverage the package.json file?

I'm writing a NPM module for a cli-based tool. 我正在为基于cli的工具编写NPM模块。 After someone installs the package, I need to read their package.json file. 有人安装软件包后,我需要阅读他们的package.json文件。 I know how to read the file in syntax. 我知道如何以语法读取文件。 My question is, how can I consistenly retrieve the package.json file and should I use relative or absolute paths. 我的问题是,如何才能一致地检索package.json文件,并且应该使用相对路径还是绝对路径。

So, after installing, my code would reside somewhere inside the node_modules folder: 因此,安装后,我的代码将驻留在node_modules文件夹内的某个node_modules

package.json // I need to require this file
node_modules/
  ↳ my-package/
    ↳ dist/
      ↳ my-package.js // the actual file running the code

Any suggestions/best practices? 有什么建议/最佳做法吗? Or is it just a matter of using the right filepath? 还是仅仅是使用正确的文件路径的问题?

Reading the package.json file is very easy, as you can simply require it: 读取package.json文件非常容易,因为您可以简单地要求它:

var package = require('./path/to/package.json');

Finding the right path is what's not so simple. 找到正确的道路并不是那么简单。

This is quite a common task and there is no simple way to achieve that with core modules but there are few modules on npm that can help you with that. 这是很常见的任务,没有简单的方法可以通过核心模块来实现,但是npm上很少有模块可以帮助您。

find-package-json: 找到包,JSON:

Easily find package.json files that you're searching for. 轻松找到您要搜索的package.json文件。 It spiders parent directories for package.json files and correctly reads the results. 它搜索用于package.json文件的父目录,并正确读取结果。 It follows an ES6 iterator design so it should be easy to implement. 它遵循ES6迭代器设计,因此应该易于实现。

parent-package-json: 父 - 包JSON:

Using parent-package-json, you can find the parent package.json, so the package.json of the module that uses your module. 使用parent-package-json,您可以找到父package.json,因此可以找到使用您模块的模块的package.json。

find-and-read-package-json: 查找和读取包JSON:

Find and read data from a package.json file. 从package.json文件中查找和读取数据。

See: 看到:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM