Search code examples
npmnpm-publish

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 ?


Solution

  • 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 .",
      ...
    },
    ...