Quickly Fix Bugs in Open Source Community Repositories

In projects, we often use many third-party NPM packages, such as Mousetrap. We usually encounter bugs that have not yet been fixed or merged by the official repository. So, what should we do in such cases? Here is a summary of the methods.

Fork the Repository and Follow the PR Process

You can fork the repository, modify the source code, submit a PR, and wait for the official team to merge and release a new package. This method is undoubtedly the best; it benefits and gives back to the community.

However, this approach’s downside is also quite noticeable. If the official longed and we urgently need the package, this solution may not be very suitable.

Adjust NPM Dependency Version

Use commit hash or a different repository address. In package.json, you can use a git commit hash to lock onto a specific version directly, so whether it is merged won’t matter. Alternatively, you can publish a package yourself after forking, but the package name cannot be the same. For example, you can add a @namespace prefix.

npm install from Git in a specific version

1
2
3
"dependencies": {
"package": "git://github.com/username/package.git#commit"
}

pkg alias

1
2
3
"dependencies": {
"package-a": "npm:@stacker/package-b@1.0.0"
}

patch-package

In addition to the above two solutions, we can use patch-package to fix bugs quickly. This approach uses git diff to generate a patch file and then applies it directly using npm scripts hooks to modify files within node_modules. Without patch-package, directly modifying source code would not be manageable under version control. patch-package offers an elegant way to handle conflicts between patches and third-party package source code that isn’t under version control.

  1. Modify the target package source code in node_modules, such as mousetrap-record.js under mousetrap.

  2. Generate a patch file.

    1
    npx patch-package mousetrap

    https://static.1991421.cn/2024/2024-10-24-115353.jpeg

  3. Configure npm scripts hook

    1
    2
    3
    "scripts": {
    "postinstall": "patch-package"
    }

    If the official repository fixes the bug in the future, we can delete the patch file, remove the package, and simply run npm install.

At the end

The above are a few methods for fixing bugs in open-source projects. Use them as needed.