Before commit

There are certain actions that must be performed before the code gets into the commit and the repository, so at least not to suffer later with rebase every time. The solution that I will describe is short and simple, but it makes a developer's life a lot easier.





The most obvious purpose is to run tests, but for me it is also building a bundle. Since I do not use watch and regularly forget to run the build command by hand, irrelevant versions of bundles often come into the commit, and the current ones have to be committed next. It turns out not very neat. For javascript, the pre-commit utility will help us. It uses hook git, but gives you the opportunity not to go into all these guts and manage the galaxy without leaving npm. Moreover, such mechanics will not be forgotten when changing the repository.





Let's go in a practical way: add the library to the project





npm i pre-commit --save-dev
      
      



In package.json, add the build command to the pre-commit section





"pre-commit": [
 "build"
],
      
      



However, the collected bundle files will not be included in the commit, since The git needs to explicitly indicate the modified and added files and adding everything looks pretty dangerous. For everything to start working properly, let's define the add-bundles command that adds bundle files.





"scripts": {
 "build": "npx rollup --config rollup.config.js",
 "add-bundles": "git add dist/*",
 "test": "echo \"Error: no test specified\" && exit 1"
},
      
      



And add the command itself to the pre-commit section





"pre-commit": [
 "build", "add-bundles"
],
      
      



Now, right before the commit, the bundle is immediately assembled and added to the commit. If you need a complete working example, there is one in the repository of this library .





This package has analogues for other hooks, for example, this one .








All Articles