mattobob
mattobob

Reputation: 865

npm, avoid publishing of src dir without using .npmignore

The npm publish command creates a tarball (with src dir) and publish it to registry.

is there a way to exclude the src dir avoiding use of .npmignore ?

Upvotes: 1

Views: 4921

Answers (3)

Joel Chu
Joel Chu

Reputation: 948

You can use the files property in your package.json to explicitly include the files you want to publish.

{
  "files": [
    "dist",
    "index.js"
  ]
}

Upvotes: 2

mattobob
mattobob

Reputation: 865

As @RobC answer, there is no other way then a custom solution for avoid using .npmignore.

Since I’m using the publish command in a Jenkins pipeline, a solution is to create a temporary .npmignore while the publish step directly in the Jenkinsfile:

echo "src/" >> .npmignore
echo "*.js" >> .npmignore
echo "*.json" >> .npmignore
echo "Jenkinsfile" >> .npmignore
curl --insecure -u ${USERPASS} 'https://my-repo/api/npm/auth' >> /home/jenkins/.npmrc
npm publish --registry https:// my-repo/api/npm/npm-local/ 

Upvotes: 0

RobC
RobC

Reputation: 25032

npm provides no other built-in feature to achieve that, so a custom solution is required.

If you really don't want to use .npmignore to keep the src directory out of your published package, then consider utilizing pre and post hooks in your npm scripts instead.

The pertinent hooks are:

  • prepublishOnly: Run BEFORE the package is prepared and packed, ONLY on npm publish ...

  • postpublish: Run AFTER the package is published.

For *nix platforms

  1. Add a prepublishOnly script to the scripts section of your package.json that moves the src directory to another location outside of your project directory prior to publishing.

  2. Also, add a postpublish script that moves the src directory back to the project directory when publishing has completed.

  3. Run npm publish (as per normal) to publish your package.

For instance:

package.json

...
"scripts": {
  "prepublishOnly": "mv src/ ../",
  "postpublish": "mv ../src .",
  ...
},
...

Note: You'll need to ensure that no other src folder/directory exists at the path location you choose to temporarily move the src directory to via your prepublish script.

Cross platform:

For a cross-platform solution consider utilizing shx. This package includes a portable mv command. In which case, configure your prepublish and postpublish scripts something like the following instead:

package.json

...
"scripts": {
  "prepublishOnly": "shx mv src/ ../",
  "postpublish": "shx mv ../src .",
  ...
},
...

Upvotes: 4

Related Questions