I know I can always just go back and edit the package.json later, but I can't help but be curious: Is there any way to run npm init
and enter a phrase with spaces in the "keywords" part of the form? For example, entering "platform api" results in the words '"platform' and 'api"' with the leading and trailing quote escaped.
No, unfortunately you cannot enter a phrase for a keyword via the npm init
command that includes spaces, such as platform api
, and expect it to become a single element within the resultant keywords
array of the package.json file.
The example below shows your desired valid result in package.json:
{
...
"keywords": [
"platform api"
],
...
}
Note: Whilst the keyword example shown above is perfectly valid in package.json
, it just cannot be achieved via input from the command-line using the npm init
command. I would consider either:
package.json
.platform-api
via the command-line when using npm init
command. - Note: that would result in platform-api
in package.json and not platform api
Your desired result cannot be achieved via the command-line using the npm init
command because of the underlying source code in the init-package-json package that the npm-cli tool utilizes.
Let's look at the pertinent part of code starting at line #210 in the file named default-input.js
. Here it is shown below:
Excerpt from default-input.js
if (!package.keywords) { exports.keywords = yes ? '' : prompt('keywords', function (s) { if (!s) return undefined if (Array.isArray(s)) s = s.join(' ') if (typeof s !== 'string') return s return s.split(/[\s,]+/) // <---- line #215 }) }
On line #215, the part that reads;
return s.split(/[\s,]+/)
the string, (i.e. the keyword(s) that you enter via the command-line), are split into an Array using the split()
method. Notice the regular expression, i.e. [\s,]+
, is used as the separator for the split()
method. This essentially splits the string wherever there is a space character(s) and/or comma(s). It's particularly this part that makes your requirement not possible.
If line #215 was changed to:
return s.split(/,\s/)
whereby a comma followed by a space was used as the separator for the split()
method. Then let's say via the npm init
command for keywords you entered:
platform api, foobar, quux
that would result in the following keywords
entry in your resultant package.json:
{
...
"keywords": [
"platform api",
"foobar",
"quux"
],
...
}
Caution: Whilst the How could it be possible section describes what changes are necessary to the source code to achieve your desired requirement, I am not implying, nor suggesting, that you change the source code.