Package json custom fields

Problem

For a project you need a custom field in your package.json? You need a custom version number?

Our you want to define parameters for your APM in your package.json?

Solution: Custom fields in package.json

Then the solution for you are custom fields. And they are actually not difficult.

All it takes is adding the new field name to your package.json. And making sure that the field name doesn’t interfere with default ones from the package.json definition.

Example 1 (custom version field, not best practice):

{
  "name": "Test",
  "version": "0.0.7",
  "our_version": "1.0.0"
}

Example 2 (custom version field, best practice):

{
  "name": "Test",
  "version": "0.0.7",
  "ourGreatCompany": {
    "ourVersion": "1.0.0"
  }
}

Explanation

Example 1 shows a custom field in your package.json for a version fields (e.g. you have a fork from a project, want to conserve their version but introduce your own version too).
It syntactically perfectly fine, yet it ignores the best practices (in this case a company related top-level key).

Example 2 shows also a custom version field, yet it uses the best practices (single top-level company key, multiple sub-keys). This reduces potential colissions.

Background

The Package.json file contains information about your project. The licensing details, location information for your code, descriptions, script set up, it´s runtime and it´s development dependencies, etc.

For all these npm has defined a standard, which keywords have which meaning.

You can´t interfere with that without breaking something.
Therefore, when you need a custom field you can´t use those keywords as key for your custom field.

Or the keyes that the CommonJS package specification (http://wiki.commonjs.org/wiki/Packages/1.1) resereved for future use.
But besides that, you can use any naming scheme imaginable.

Good practices are:

  • avoid prefixes _ and $
  • prefer a single top-level key (with multiple sub-keys)

It might be an edge case to need a custom field in your package.json. But sometimes it´s just required. E.g. I was working on a project where the original version field needed to be conserved so that we can update our fork from the original source.

In such a case it’s helpful to know the rules and how to do it. Without introducing other problems.

Let me know if it helped.

Best,

Frank

Sources:

https://stackoverflow.com/questions/10065564/add-custom-metadata-or-config-to-package-json-is-it-valid

https://areknawo.com/whats-what-package-json-cheatsheet/

Leave a Reply