Blog Mar 1, 2018 · 2 min read

Forking a npm package

If you need to make some change to a package you use, you don't need to publish your changes to npm. The npm and Yarn clients let you install dependencies directly from GitHub. So if you had to fork, let's say the history package, you can install your fork with one of the following:

npm install github:your_github_username/history
# or
yarn add github:your_github_username/history

And every time you need to update it just run upgrade with the package name instead of the short repo notation:

npm upgrade history
# or
yarn upgrade history

The problem is that for many packages you need to build the source before using it. These build files are included in the published package you download from the npm registry, but aren't available in the GitHub repository. This happens because they are listed in the project's .gitignore, since they aren't source and don't belong in source control.

One solution is to just change the .gitignore file and publish those files. An alternative option is to use a prepare script instead.

Going back to our example, this is how history's package.json looks like:

  "name": "history",
  "version": "4.7.2",
  "description": "Manage session history with JavaScript",
  // ...
  "scripts": {
    "start": "webpack-dev-server -d --content-base ./ --history-api-fallback --inline modules/index.js",
    "build": "node ./tools/build.js",
    "prepublishOnly": "node ./tools/build.js",
    "clean": "git clean -fdX .",
    "lint": "eslint modules",
    "test": "karma start --single-run"
  // ...

Simply replace prepublishOnly with prepare and you should be good to go. In recent versions of npm and Yarn, prepare is executed after the package is installed from GitHub.