You can do that using lint-staged:
Linting makes more sense when running before committing your code. By doing that you can ensure no errors are going into repository and enforce code style. But running a lint process on a whole project is slow and linting results can be irrelevant. Ultimately you only want to lint files that will be committed.
This project contains a script that will run arbitrary npm and shell tasks with a list of staged files as an argument, filtered by a specified glob pattern.
Install lint-staged and husky, which is required for pre-commit hooks, with this command:
npm install --save-dev lint-staged husky
Change your package.json as follows:
{
"scripts": {
"precommit": "lint-staged"
},
"lint-staged": {
"*.js": [
"prettier --write",
"git add"
]
}
}
Answer from str on Stack OverflowHow to run prettier check ?
How Do I Run Prettier Only on Files That I Want to Commit?
command line interface - Run prettier from CLI with config in package.json - Stack Overflow
node.js - Prettier on-save different to running via npm - Stack Overflow
Videos
» npm install prettier
You can do that using lint-staged:
Linting makes more sense when running before committing your code. By doing that you can ensure no errors are going into repository and enforce code style. But running a lint process on a whole project is slow and linting results can be irrelevant. Ultimately you only want to lint files that will be committed.
This project contains a script that will run arbitrary npm and shell tasks with a list of staged files as an argument, filtered by a specified glob pattern.
Install lint-staged and husky, which is required for pre-commit hooks, with this command:
npm install --save-dev lint-staged husky
Change your package.json as follows:
{
"scripts": {
"precommit": "lint-staged"
},
"lint-staged": {
"*.js": [
"prettier --write",
"git add"
]
}
}
I found that just running:
prettier --write $(git diff --name-only --diff-filter d | grep '\.js$' | xargs)
was quite enough for my needs, just made an alias and used that.
I ran into this error while using a .prettierrc.json file, and the problem was that the file was encoded in UTF-16LE, not UTF-8. Saving the file as UTF-8 fixed this for me.
The root cause of this issue was following the documentation that recommended echo {}> .prettierrc.json to create the file. On Windows powershell, this creates a UTF-16LE file, not a UTF-8 file.
More discussion can be found at this github issue
According to https://prettier.io/docs/en/configuration.html configuration in package.json has the highest precedence, so you should be able to call:
prettier ./src/basic-sample.js
or
prettier --write ./src/basic-sample.js
I'm doing this from within an package.json script, but that shouldn't make any difference.
» npm install prettier-format