Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

node.js - Add custom metadata or config to package.json, is it valid?

I have seen (don't remember where) a package.json file with custom keys starting with an underscore:

{
    "name": "application-name"
  , "version": "0.0.1"
  , "private": true
  , "dependencies": {
      "express": "2.4.7"
    , "jade": ">= 0.0.1"
  }
  , "_random": true
}

Are you allowed to do this? Is it still valid? If this is allowed, is there any documentation on the rules?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

tl;dr:

  • Yes, you're allowed to add custom entries to package.json.
  • Choose a key name:
    • not already defined (details below)
    • not reserved for future use (details below)
    • avoid prefixes _ and $
    • and preferably use a single top-level key in which to nest your custom entries.

E.g., if you own domain example.org, you could store a custom random key as follows, inside a top-level key in reverse-domain-name notation with _ substituted for . and, if applicable, -(see comments) (e.g., org_example):

{
    "name": "application-name"
  , "version": "0.0.1"
  , "private": true
  , "dependencies": {
      "express": "2.4.7"
    , "jade": ">= 0.0.1"
  }  
  , "org_example": {
      "random": true
  }
}

To read such custom properties, use the following technique:

require("./package.json").org_example.random // -> true

npm's package.json file format mostly complies with the CommonJS package specification:

As for choosing custom keys: the CommonJS package specification states (emphasis mine):

The following fields are reserved for future expansion: build, default, email, external, files, imports, maintainer, paths, platform, require, summary, test, using, downloads, uid.

Extensions to the package descriptor specification should strive to avoid collisions for future standard names by name-spacing their properties with innocuous names that do not have meanings relevant to general package management.

The following fields are reserved for package registries to use at their discretion: id, type. All properties beginning with _ or $ are also reserved for package registries to use at their discretion.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...