Webpack ~ ESLint - rohit120582sharma/Documentation GitHub Wiki
Linter is a program that checks our code for any error or warning that can cause bugs.
JavaScript’s linter, ESLint, is a very flexible linting program that can be configured in many ways.
Let’s install ESLint into our project:
npm install --save-dev eslint eslint-loader babel-eslint eslint-config-react eslint-plugin-react
- eslint is the core dependency for all functionalities
- eslint-loader enables us to hook eslint into webpack
- babel-eslint is a parser that enables eslint to lint all valid ES6+ codes
- eslint-config-react and eslint-plugin-react are both used to enable ESLint to use pre-made rules
Since we already have webpack, we only have to modify the config slightly:
module.exports = {
// modify the module
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader'] // include eslint-loader
}
]
},
};
Then create an eslint config file named .eslintrc with this content:
{
"parser": "babel-eslint",
"extends": "react",
"env": {
"browser": true,
"node": true
},
"settings": {
"react": {
"version": "detect"
}
}
}
This configuration tells ESLint to:
- Parse the code using babel-eslint before you're checking it.
- Check if all the rules from our React rules config is passed.
- Take global variables from the environment of browser and node.
- If it’s React code, take the version from the module itself. That way the user won’t have to specify the version manually.
- Rather than specifying our own rules manually, we simply extend react rules which were made available by eslint-config-react and eslint-plugin-react.
Unfortunately the only way to really figure out how to fix ESLint errors is by looking at the documentation for rules. There’s a quick way to fix ESLint errors by using eslint--fix, and it’s actually good for a quick fix.
Let’s add a script on our package.json file:
"scripts": {
"eslint-fix": "eslint --fix \“src/**/*.js\“", // the eslint script
},