This little guide works to set the last version of husky and use ESLint.
Initialize an NPM project
mkdir app
cd app
Inside the project execute this command:
npm init
Then, just fill the questions or press enter several times to get the node_modules
generated.
Initialize Git
In order to use Husky Hooks it requires to set previously Git:
git init
Ignore node_modules directory from git
Generate .gitignore
file:
touch .gitignore
Edit the .gitignore
file and fill it with this line, to set a reference to exclude node_modules
directory:
node_modules
Save and exit
Install Husky
npm i -D husky
Install Lint Staged
npm i -D lint-staged
Set a husky install command
In package.json file add a script to generate husky files (add the "prepare" script line):
add this line into scripts object:
"prepare": "husky install",
The package.json file should look like this:
{
...
"main": "index.js",
"scripts": {
"prepare": "husky install",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
...
}
Then just run the command on terminal:
npm run prepare
Install ESLint
Install ESLint:
npx eslint --init
It would run a prompt with some questions: fill it as makes sense for your project, here an example:
✔ How would you like to use ESLint? · yes
✔ What type of modules does your project use? · commonjs
✔ Which framework does your project use? · none
✔ Does your project use TypeScript? · no
✔ Where does your code run? · browser, node
✔ What format do you want your config file to be in? · JavaScript
Local ESLint installation not found.
The config that you've selected requires the following dependencies:
eslint@latest
✔ Would you like to install them now? · yes
✔ Which package manager do you want to use? · npm
To select multiple options press space-bar.
Create a configuration file to run ESLint with lint-staged:
touch .lintstagedrc
Edit .lintstagedrc
to check .js
and .ts
extension files with this JSON content:
{
"*.(js|ts)" : ["eslint"]
}
Then save the file and exit.
Set a pre-commit hook running lint-staged
npx husky add .husky/pre-commit "npx lint-staged"
It would generate a new file in ".husky/pre-commit" and fill the file with the npx lint-staged
command to be executed on that hook.
Test the installation
Create an index.js
file:
touch index.js
Fill the index.js
file with this code:
function sum(a, b) {
return a + b;
}
console.log(sum(1, 2));
Now save and exit.
Create a commit
git add .
git commit -m "add a file"
Then it should run ESLint, check syntax and stop the commit until it fixes the code.
The output should look like this:
Advance options
- You can set a common syntax for ESLint by running again:
npx eslint --init
And select the syntax rules desired.
- To automatically fix spaces, indentation, extra commas, etc you can set the flag
--fix
in.lintstagedrc
file:
{
"*.(js|ts)": [
"eslint --fix"
]
}
Thanks for reading.
Top comments (0)