问题
I like the automated organize feature in VSCode, but having it doing it on every save has given me some trouble.
...
"editor.codeActionsOnSave": {
"source.organizeImports": true
},
...
Is it possible to set up some git hooks that organize the imports (either via vscode or some other script/lib) when I stage them?
Issues
If I hit save too early (do it to kick off prettier all the time) before I have used the imported methods - then it removes it and I have to write the import again.
If I break the code (.jsx) and something appears to not be used and I hit save (to trigger prettier), then it removes the imports. I then have to import them again.
回答1:
There is some form of hook that can be applied when running git add
: filters defined in gitconfig
and .gitattributes
.
See this section of git book for detailed explanations.
Here are the sketches from the documentation (it illustrates how you can configure a filter to run on *.txt
files) :
- when running
git add
:
- when running
git checkout
:
You can define in your gitconfig
a filter, which consists of two commands to "clean" and "smudge" :
$ git config --global filter.jsximports.clean fiximports
$ git config --global filter.jsximports.smudge cat
and edit the .gitattributes
file to apply this filter on jsx files
*.jsx filter=jsximports
The script to apply may be tslint --fix
, with the ordered-imports rule.
Actually : tslint
's rule seem to have its own implementation, but it does something similar (see https://github.com/palantir/tslint/pull/4064)
In this answer : https://stackoverflow.com/a/57458656/86072
user thorn points to this npm package :
https://www.npmjs.com/package/organize-imports-cli
which calls organizeImports from cli
来源:https://stackoverflow.com/questions/56449677/vscode-trigger-organizeimports-when-git-staging