This tutorial is part 2 of 2 in 'Webpack with ESLint'-series.
- Part 1: How to set up Webpack 5 with Babel
So far, you should have a working JavaScript with Webpack application. In this tutorial, we will take this one step further by introducing ESLint for an enforced unified code style without code smells. Code style becomes an important topic for developers. If you just code for yourself, it might be alright to violate best practices. However, in a team of developers you have to have a common code style as foundation. You should follow the same rules to make your code look alike. It helps others developers to read your code, but also to avoid code smells.
ESLint
ESLint in JavaScript helps you to set up rules and to enforce code style across your code base. Let's get started by installing the eslint library (node package). You can install it in your project from your project's root directory on the command line:
npm install --save-dev eslint
You may also want to install the ESLint extension/plugin for your editor/IDE. For instance, in VSCode you can find the ESLint extension on their marketplace. Afterward, you should see all the ESLint errors in your editor's/IDE's output.
Continue Reading:
How use ESLint in VSCode
ESLint + Webpack + Babel
Since the project uses Webpack, you have to tell Webpack that you want to use eslint in your build process. Therefore you can install eslint-webpack-plugin on the command line to your project's dependencies from your project's root folder:
npm install --save-dev eslint-webpack-plugin
Next, you can use the new Webpack plugin for ESLint in your Webpack webpack.config.js file:
...
const ESLintPlugin = require('eslint-webpack-plugin');
module.exports = {
...
plugins: [new ESLintPlugin()],
...
};
(Video) Webpack 5: Setup Webpack 5
Now, all source code that goes through Weback will be checked by ESLint automatically. Once you start your application, it will output an error though: "No ESLint configuration found". You need this file to define your ESLint configuration. Create it in your project's root directory on the command line:
touch .eslintrc
Then, create an empty ESLint rule set in this new .eslintrc file:
{
"rules": {}
See AlsoLaravel - The PHP Framework For Web ArtisansThis will make you more efficient at debugging Webpack unspecified build errors - inDepthDevReact with Typescript and Webpack}
Later on you can specify rules in this file. But first, let's try to start your app again. You might run (again) into Parsing errors such as "The keyword 'import' is reserved" or "The keyword 'export' is reserved". The error happens, because ESLint does not know about Babel enabled JavaScript features yet. For instance, the import
or export
statements are JavaScript ES6 features. Therefore, you have to use babel-eslint node package to lint source code that is valid Babel interpreted JavaScript. From your project's root directory type:
npm install --save-dev @babel/eslint-parser
Then, in your .eslintrc configuration file, add @babel/eslint-parser as parser:
{
"parser": "@babel/eslint-parser",
"rules": {}
}
Note: If the previous error regarding Babel enabled JavaScript features still shows up in your IDE/editor -- because you may have installed an ESLint plugin/extension, restart your IDE/editor and check whether the error still shows up. It shouldn't.
You should be able to start your application without any ESLint errors now. There are no errors displayed, because you didn't specify any rules yet.
ESLint Rules
ESLint rules apply for a lot of different code style use cases. Check out the list of available ESLint rules yourself. For the sake of learning about ESLint rules, let's add our first rule in the .eslintrc configuration file for ESLint:
{
...
(Video) #4 Set up Webpack 5, ES6 with ESLint, PostCSS with Stylelint, CSSNANO in WordPress Plugin"rules": {
"max-len": [1, 70, 2, {ignoreComments: true}]
}
...
}
The rule checks the length of characters in a line of code. If the length is more than 70 characters, you will get a warning once you start your application with npm start
or in your IDE/editor in case a plugin or extension for ESLint. Try to call up this warning by writing a line of code longer than 70 characters. ESLint should tell you something like: "This line has a length of <XX>
. Maximum allowed is 70". You can adjust the rule to allow some more characters:
{
...
"rules": {
"max-len": [1, 120, 2, {ignoreComments: true}]
}
...
}
If you still see warnings, it is your first chance to improve the code style in your codebase.
Exercises:
- Fix all the code style violations in your source code
- Try out more ESLint rules yourself
Now, it would be very tidious to come up with a set of ESLint rules for every JavaScript project. That's why it's possible to share them as libraries (node packages). There are various shareable ESLint configs out there, however, one of the most popular one is the Airbnb ESLint configuration based on Airbnb's Style Guide. You can install the configuration in addition to all its peer dependencies with the following command on the command line from your project's root directory:
npx install-peerdeps --dev eslint-config-airbnb
Afterward, you can introduce it in your .eslintrc configuration file for ESLint:
{
(Video) Webpack 5 Tutorial for Beginners"parser": "@babel/eslint-parser",
"extends": ["airbnb"],
"rules": {
"max-len": [1, 70, 2, { "ignoreComments": true }]
}
}
Note: It's up to you to keep your own ESLint rules (e.g. max-len from before) to extend the ESLint rule set from Airbnb. However, my recommendation would not be to come with your own ESLint rules. Instead, pick one of the more popular ESLint configuration by large companies and follow their guidance. If you are already advanced in JavaScript, you (and your team) can start to add your own flavor to the ESLint rules by extending it or by coming up with a configuration entirely on your own.
{
"parser": "@babel/eslint-parser",
"extends": ["airbnb"]
}
After starting your application on the command line again or checking the output in your IDE/editor with an installed ESLint plugin/extension, you may see new ESLint warnings/errors popping up. That's a good point in time to start fixing them.
Exercises:
- Fix all your ESLint violations
- Get to know other reputable ESLint configurations (e.g. Google, Standard) other than Airbnb's ESLint configuration
How to disable ESLint Rules
Sometimes you might see a lot of ESLint rule violations on your command line or in your IDE/editor. Often it is up to you to fix them to follow the common best practices. However, whenever you are unsure about the ESLint warning, search it in your favorite search engine and evaluate whether you want to have this ESLint rule or not. You can either fix the warning in the mentioned source code file or remove/disable the rule altogether, if you think you don't need it.
In case you want to remove a ESLint rule globally, just remove it from your .eslintrc file in case you specified it yourself and it doesn't come from any popular style guide (e.g. Airbnb). If the latter is the case, you can only disable the rule. For instance, the no-unused-vars ESLint rule from Airbnb's ESLint configuration could be disable the following way:
{
"parser": "@babel/eslint-parser",
"extends": ["airbnb"],
"rules": {
(Video) Why I always use ESLint in my projects"no-unused-vars": 0
}
}
However, you can also disable your own or extended ESLint rules in the respective source code file:
/* eslint-disable no-unused-vars */
const myUnusedVariable = 42;
/* eslint-enable no-unused-vars */
Also you can disable an ESLint rule in the whole or rest of a file by not enabling the ESLint rule again:
/* eslint-disable no-unused-vars */
const myUnusedVariable = 42;
Now, you should have all the ESLint knowledge at your hands to have a unified code style with best practices by using a popular ESLint configuration such as the one from Airbnb. You also know how to add your own rules, how to show violations in your IDE/editor/command line, how to fix violations, and how to remove/disable ESLint rules.
How to install ESLint globally
The tutorial has shown you how to install ESLint on a per project basis with npm install --save-dev eslint
. Also you stepped through the whole process of setting up the ESLint configuration and installing a shareable ESLint configuration yourself. However, there is an more effortless way of doing it in the end. You can install ESLint globally to make it kinda accessible for all of your JavaScript projects with npm install -g eslint
.
Still, once your JavaScript project is set up, you need to run eslint --init
in the root directory of your project on the command line which will install a local copy of ESLint for your project again. Also you will see a command line prompt that you can step through to set up your ESLint configuration dynamically. In the end, that's my recommended way of setting up ESLint for your JavaScript project.
This tutorial is part 1 of 3 in the series.
- Part 2: How to use Prettier in VS Code
- Part 3: How to use Prettier with ESLint
This tutorial is part 1 of 3 in the series.
- Part 2: How to set up React with Webpack and Babel
- Part 3: How to use ESLint in React
Continue Reading:
How to set up an advanced Webpack application
FAQs
How to set up ESLint with webpack? ›
Setting up ESLint with Webpack and TypeScript
Install dev dependencies: eslint-loader : eslint webpack loader. @typescript-eslint/parser : The parser that will allow ESLint to lint TypeScript code. @typescript-eslint/eslint-plugin : A plugin that contains ESLint rules that are TypeScript specific.
- npm install eslint-webpack-plugin --save-dev. or.
- yarn add -D eslint-webpack-plugin. or.
- pnpm add -D eslint-webpack-plugin. Note: ...
- npm install eslint --save-dev. or.
- yarn add -D eslint. or.
- pnpm add -D eslint. Then add the plugin to your webpack config.
This is eslint-webpack-plugin 3.0 which works only with webpack 5. For the webpack 4, see the 2. x branch.
How to create ESLint configuration file? ›- Install the ESLint package in your project: npm install --save-dev eslint. ...
- Add an .eslintrc file in one of the supported configuration file formats. ...
- Add configuration to the .eslintrc file. ...
- Lint code using the ESLint CLI: npx eslint project-dir/ file1.js.
Run ESLint --fix From npm Script
You must add two dashes after your command to run an npm script with a CLI flag. You can't run npm run <script> --flag . In situations where you're starting an npm script from within another npm script, you must also add the two dashes before passing along the CLI flag.
The pluggable linting utility for JavaScript and JSX
ESLint is an open source project that helps you find and fix problems with your JavaScript code. It doesn't matter if you're writing JavaScript in the browser or on the server, with or without a framework, ESLint can help your code live its best life.
Configuration. const HtmlWebpackPlugin = require('html-webpack-plugin'); const webpack = require('webpack'); //to access built-in plugins const path = require('path'); module. exports = { entry: './path/to/my/entry/file. js', output: { filename: 'my-first-webpack.
How do I use CSS modules in webpack? ›In the following code block, css-loader and style-loader are used together. Similar to babel-loader , we can load CSS files to style our pages like so: module: { rules: [ { test: /\\. js$/, loader: "babel-loader", exclude: "/node_modules/", }, // CSS rules { test: /\\.
Does ESLint run automatically? ›You can set up ESLint to run auto-fix every time you press CTRL+S (or COMMAND+S ). For ESLint to work correctly on file same, you must change the Visual Studio Code preferences. Go to File > Preferences > Settings (or Code > Preferences > Settings).
How do you use ESLint in a project? ›install eslint as an extension in your VS Code Editor. Install eslint as a global package using npm. initialize eslint in your javascript project. modify your eslint configuration file in your project.
Does ESLint need Babel? ›
You only need to use babel-eslint if you are using types (Flow) or experimental features not supported in ESLint itself yet. Otherwise try the default parser (you don't have to use it just because you are using Babel).
How do I know if ESLint is working? ›If ESLint is running in the terminal but not inside VSCode, it is probably because the extension is unable to detect both the local and the global node_modules folders. To verify, press Ctrl + Shift + U in VSCode to open the Output panel after opening a JavaScript file with a known eslint issue.
What does ESLint command do? ›The ESLint Command Line Interface (CLI) lets you execute linting from the terminal. The CLI has a variety of options that you can pass to configure ESLint.
Where is the ESLint config file? ›The ESLint configuration is in the ./node_modules/@spm/eslint-config/index. js file. To check the code for ESLint violations, run the following command in the application root directory.
How do I add or code to ESLint? ›Configure VSCode Settings to use ESLint for Formatting
Click that tiny icon in the top-right that looks like a piece of paper with a little arrow. The first one turns on ESLint for formatting, and the next 3 make it do the formatting when you hit save. That should do it! Save the settings file and close it, we're done.
ESLint supports configuration files in several formats: JavaScript - use .eslintrc.js and export an object containing your configuration. JavaScript (ESM) - use .eslintrc.cjs when running ESLint in JavaScript packages that specify "type":"module" in their package.json .
Should I install ESLint globally or locally? ›It is also possible to install ESLint globally rather than locally (using npm install eslint --global). However, this is not recommended, and any plugins or shareable configs that you use must be installed locally in either case.
How do I run lint command? ›- scripts. simply add in scripts section in your package.json "lint": "eslint src" ...
- run. then to run use: $ yarn lint. ...
- config.
ESLint is a modern linting tool for JS development to make your code consistent and bug free. Use npm install eslint --global to install ESLint globally. Go to your project in the terminal and run eslint --init to initiate and setup linting for your project.
Does ESLint work with json? ›You can run ESLint on individual JSON files or you can use the --ext flag to add JSON files to the list.
What is the difference between lint and ESLint? ›
Linters check your code for syntax errors and highlight errors to make sure you can quickly find and fix them. ESLint is a linter that you can integrate into your Visual Studio Code setup in order to ensure code integrity.
What are the advantages of using ESLint? ›ESLint can make your code style consistent, avoid errors, and improve code quality. One of the first things to do when creating a Javascript project is adding ESLint into your Javascript code. You are provided with tons of rules and even plugins to choose from to make your code bug-free.
Why is it called linting? ›The term "lint" was derived from lint, the name for the tiny bits of fiber and fluff shed by clothing, as the command should act like the lint trap in a clothes dryer, detecting small errors to great effect.
What is the difference between plugins and loaders in webpack? ›Loaders work at the individual file level during or before the bundle is generated. Plugins: Plugins work at bundle or chunk level and usually work at the end of the bundle generation process. Plugins can also modify how the bundles themselves are created.
Can webpack work without config file? ›Apart from using the webpack-cli from a terminal, you can also use webpack in your project via a configuration file. But with the recent versions of webpack, we can use it in our project without a configuration file. We can use webpack as a value of one of the commands in our package. json file — without any flag.
Where should I put webpack config? ›The easiest way to get your webpack. config. js file to work is to place it at the top level of your project's folder structure along with your package. json file.
What are four core concepts of webpack? ›There are four basic concepts in webpack: entry , output , modules and plug-ins . These configurations are added in webpack.
How to configure CSS in webpack? ›To be able to use CSS in your webpack app, you need to set up a new loader. Out-of-the-box, webpack only understands Javascript and JSON. With a loader, you can translate another type of file to a format that webpack understands and can work with. There are many webpack loaders and each loader has a specific purpose.
How do I use API in webpack? ›- You create a file with a module (file that exports a function or class)
- Webpack detects the module.
- Webpack transforms this module into the format of your choice.
- Webpack then adds this module into (typically) one javascript file called a "bundle". It's even called bundle. js in most cases.
- Install eslint-webpack-plugin as a development dependency;
- Delete eslint-loader dependency;
- Remove eslint-loader from the common rules array: ...
- Create a new plugins array similar to the rules one and add the ESLintPlugin plugin to it;
Can webpack compile SCSS? ›
sass-loader is a loader for Webpack for compiling SCSS/Sass files. style-loader injects our styles into our DOM. css-loader interprets @import and @url() and resolves them.
How do I load CSS into webpack? ›To be able to use CSS in your webpack app, you need to set up a new loader. Out-of-the-box, webpack only understands Javascript and JSON. With a loader, you can translate another type of file to a format that webpack understands and can work with. There are many webpack loaders and each loader has a specific purpose.
What is new in webpack 5? ›webpack 5 also brings a new experiments configuration option with support for WebAssembly, Async Web Assembly, Top Level Await, and outputting your bundle as a module (previously only possible with rollup).
What can I use instead of eslint-loader? ›eslint-loader is deprecated. The replacement, is eslint-webpack-plugin .
What is faster than webpack? ›Esbuild also takes a traditional bundling approach, but is simply lightning fast. Written in go instead of JavaScript and making healthy use of parallelization, Esbuild is estimated to be 50–100x the speed of other bundlers including Parcel and Webpack.
What is better than webpack? ›gulp, Babel, Parcel, Browserify, and Grunt are the most popular alternatives and competitors to Webpack.
Why is webpack so slow? ›However, due to the additional packaging process, the building speed is getting slower as the project grows. As a result, each startup takes dozens of seconds (or minutes), followed by a round of build optimization.
How do I bundle a JavaScript file in webpack? ›You can bundle your JavaScript using the CLI command by providing an entry file and output path. Webpack will automatically resolve all dependencies from import and require and bundle them into a single output together with your app's script.
Why does webpack need loaders? ›They allow you to pre-process files as you import or “load” them. Thus, loaders are kind of like “tasks” in other build tools and provide a powerful way to handle front-end build steps. Loaders can transform files from a different language (like TypeScript) to JavaScript or load inline images as data URLs.
How do I bundle HTML files with webpack? ›To configure Webpack to bundle HTML we'll use our first plugin, a dependency called HtmlWebpackPlugin. Remember, loaders offer functionality to files before Webpack bundles them, whereas plugins modify the entire bundle itself.