background
First of all, the problem happened like this. When the third-party plug-in PDFVuer was used in the project, we needed to display the sealed PDF successfully. At this time, we found that the article could be displayed well, but the company’s signature could not be displayed. However, the signature modification code is in the node_modules directory. After all, NPM install needs to manually modify the files in node_modules. Suddenly I started to feel bad. It was hard to feel bad but I had to do something about it
At first, I came up with two solutions:
- Fork someone else’s code into your repository, modify it, and install the plug-in from your repository.
- Download someone else’s code locally, place it in the SRC directory, modify it and import it manually. There are a number of inconveniences, such as encapsulating components individually, which is cumbersome and time consuming, and can make the project look bloated.
However, either of the above methods is too complicated. I changed one or two lines of code in a file, but had to copy the whole project so bloated that I might forget where THE modification was made in the end, and it is troublesome to update. We need to update the code manually every time, and we cannot synchronize the update with the plug-in. In this case I turned my head and began my quest for knowledge… Then I found an elegant solution to change the dependency packages in node_modules with patch-package.
The solution
1. Run commands to install patch-package
`npm install patch-package --save-dev`
Copy the code
2. Modify the package.json file in the root directory of the project
Add "postinstall": "patch-package" to scripts in package.json fileCopy the code
3. Manually modify the source code in the node_modules dependency package
4. Run the NPX patch-package package-name command to manually create a patch file
`npx patch-package package-name`
Copy the code
Package-name indicates the name of the dependent package to be modified. After you run this command, a patches folder is automatically created in the root directory of the project, and a package-name+version.patch file is displayed in the folder. As shown in figure:
For example: I want to modify the file under pdfjs-dist so I run the command: NPX patch-package pdfjs-dist
5. Test whether the patch package is valid
Manually delete the node_modules file in the project (forcibly delete the node_modules folder: rimraf node_modules) and re-run NPM install to install the node_modules dependency package. After the installation is successful, check the node_modules dependency package file to see if the modified code still exists. If the modified code still exists, the patch file has taken effect. If the modified code does not exist, the patch file has not taken effect.