Skip to main content

ESLint

what is .eslintrc

An .eslintrc file is a configuration file used by the ESLint tool to specify rules for linting JavaScript code. ESLint is a popular JavaScript linter that can detect and report on various types of errors and stylistic issues in your code.

The .eslintrc file can be used to configure ESLint with specific rules and settings for your project. For example, you can specify which ECMAScript version you are using, which plugins to use, and which rules to enable or disable. You can also specify specific environments (such as 'browser' or 'node') and global variables that should be considered when linting the code.

ESLint supports several formats for the configuration file, including .eslintrc.js, .eslintrc.yaml, and .eslintrc.json. The .eslintrc file can be placed in the root of your project directory or in a subdirectory, and ESLint will automatically find and use it when you run the tool.

{
"files": [
"*.html"
],
"parser": "@html-eslint/parser",
"extends": [
"plugin:@html-eslint/recommended"
],
"rules": {
"@html-eslint/require-doctype": "off",
"@html-eslint/indent": "off",
"@html-eslint/element-newline": "error"
}
}

Setting up ESLint for an Express API project involves configuring ESLint rules and plugins to enforce coding style and best practices. Here's a step-by-step guide to setting up an .eslintrc.js file for an Express API project:

  1. Install ESLint as a development dependency by running the following command in your project directory:
npm install eslint --save-dev
  1. Initialize ESLint configuration by running the following command:
npx eslint --init

This command will prompt a series of questions to set up your ESLint configuration.

  1. Select the following options when prompted:

    • How would you like to use ESLint?: Choose "To check syntax, find problems, and enforce code style."

    • What type of modules does your project use?: Choose the appropriate module system based on your project setup (e.g., "CommonJS" if using require or "ECMAScript modules" if using import/export).

    • Which framework does your project use?: Select "None of these."

    • Does your project use TypeScript?: Choose "No" if you're not using TypeScript.

    • Where does your code run?: Select "Node" to indicate that your code runs in a Node.js environment.

    • How would you like to define a style for your project?: Choose the style guide you prefer, or select "Use a popular style guide" and choose from the available options (e.g., "Airbnb" or "Standard").

    • What format do you want your config file to be in?: Choose "JavaScript" to generate an .eslintrc.js file.

  2. After answering the questions, ESLint will install the necessary packages and generate the .eslintrc.js file with the chosen configuration.

  3. Customize your .eslintrc.js file to include specific rules and plugins tailored for Express API development. Here's an example configuration that includes rules for Node.js and Express:

module.exports = {
env: {
node: true,
es2021: true
},
extends: [
'eslint:recommended',
'plugin:node/recommended'
],
parserOptions: {
ecmaVersion: 12
},
rules: {
// Add specific rules as needed
},
plugins: [
'node'
]
};

This configuration enables the recommended ESLint rules and plugins for Node.js (eslint:recommended and plugin:node/recommended). You can further customize the rules section to match your preferred coding style and project-specific requirements.

  1. Optionally, you can install additional ESLint plugins and configure rules specific to Express. For example, you can install the eslint-plugin-express package to enable rules for Express development:
npm install eslint-plugin-express --save-dev

Then, add 'plugin:express/recommended' to the extends array in your .eslintrc.js file:

module.exports = {
extends: [
// ...
'plugin:express/recommended'
],
// ...
plugins: [
// ...
'express'
]
};

This configuration enables additional rules and recommendations for Express development.

That's it! You now have an .eslintrc.js file configured for your Express API project. ESLint will enforce the specified rules and provide feedback on code style and potential issues when you run it against your project files using the eslint command.

Typescript

"extends": "./node_modules/gts/": This line indicates that the ESLint configuration extends the rules defined by the gts package, which stands for Google TypeScript Style. By specifying the path ./node_modules/gts/, it directly uses the configuration provided by the gts package installed in the node_modules directory of the project. This means the project adheres to the coding style and rules defined by Google's TypeScript style guide, with some customizations as defined under the rules property.

The Google TypeScript Style Guide (gts) is a set of coding conventions and rules for TypeScript programming developed and used by Google. It aims to provide a consistent coding style for TypeScript projects, making code more readable and maintainable. The style guide covers various aspects of TypeScript programming, including formatting, naming conventions, best practices, and recommendations for structuring code.

Key aspects of the Google TypeScript Style Guide include:

  1. Code Formatting: It enforces specific formatting rules to ensure code consistency across different projects. This includes preferences for indentation, line length, use of spaces over tabs, and more.

  2. Naming Conventions: The guide specifies naming conventions for variables, functions, classes, interfaces, etc., to improve code readability and maintainability. For example, it recommends using camelCase for variables and functions, and PascalCase for classes and interfaces.

  3. Type Safety: It encourages practices that enhance type safety, such as avoiding the any type, preferring interfaces over complex type literals, and using union types for better type checking.

  4. Best Practices: The guide includes best practices for writing clean and efficient TypeScript code. This covers recommendations on how to use functions, classes, modules, and other TypeScript features effectively.

  5. Linting Rules: gts provides a set of ESLint rules that enforce the style guide. These rules help developers automatically check their code for style violations and maintain consistency across the project.

  6. Tooling Support: The gts package comes with tooling support to easily set up and enforce the Google TypeScript Style in projects. It includes a pre-configured ESLint setup, and scripts for checking and fixing code style issues.

To use gts in a project, developers can install the gts package via npm or yarn. Once installed, it can be integrated into the project's build and development processes, allowing automated enforcement of the style guide through linting and formatting tools.

The Google TypeScript Style Guide is designed to be practical and adaptable, making it suitable for a wide range of TypeScript projects, from small libraries to large-scale applications. By following this style guide, teams can improve code quality, enhance collaboration, and streamline the development process.

JavaScript

The line /* eslint-disable no-param-reassign */ at the beginning of your rhymeRouter.js file is a directive to disable a specific rule of ESLint for the entire file. ESLint is a static code analysis tool used in JavaScript and Node.js projects to identify problematic patterns or code that doesn't adhere to certain style guidelines.

The rule being disabled here, no-param-reassign, is intended to prevent reassignment of function parameters. This is because modifying the objects passed as parameters can lead to unexpected behavior in the calling code, making the code harder to understand and maintain. However, in some cases, especially when working with middleware in Express.js, it's common to modify the req (request) or res (response) objects by adding properties or changing their state. This is often done for practical reasons, such as attaching data or a model instance that will be used by subsequent middleware or route handlers.

By disabling this rule at the top of the file, it tells ESLint to ignore all instances where function parameters are reassigned within this file, preventing ESLint from reporting these as warnings or errors. This can make the development process smoother, especially when such reassignments are a necessary part of the application's logic, as is often the case in Express.js applications. However, it's important to use this directive judiciously, as disabling linting rules can potentially hide issues that could lead to bugs or maintainability problems.

ESLint for formatting HTML files

{
"extends": ["plugin:html/recommended"],
"plugins": ["html"],
"rules": {
"html/indent": ["error", "tab"],
"html/void-style": ["error", "empty"],
"html/self-closing": ["error", {
"html": {
"void": "always",
"normal": "never",
"component": "always"
},
"svg": "always",
"math": "always"
}]
}
}

Let's break down what each part of this configuration does:

  • extends: This specifies that we want to use the recommended configuration for the eslint-plugin-html plugin. This includes a set of rules that are recommended for most HTML projects.
  • plugins: This lists the plugins that we are using. In this case, we are only using the eslint-plugin-html plugin.
  • rules: This is where we configure the specific rules that we want to enable or modify. In this example, we are setting three rules:
    • html/indent: This rule requires that HTML elements are indented using tabs.
    • html/void-style: This rule requires that void elements (like <img> and ) have an empty style, rather than using a closing slash (like <img / />).
    • html/self-closing: This rule requires that certain types of elements (like SVG and MathML) are always self-closing, and that other types (like normal HTML elements and custom components) are never self-closing.

You can adjust these rules to match your preferred HTML formatting style. Additionally, you may want to configure other rules for the JavaScript portions of your codebase, depending on your preferences and coding standards.

configure ESLint for HTML files

rules set up ESLint for HTML files

  • html/indent: This rule enforces a consistent indentation for HTML code. The first argument to the rule is the severity of the error, which is set to "error" in this case. The second argument is the indentation style, which is set to "tab". You can change this to any number of spaces or a different character to match your preferred indentation style.

  • html/void-style: This rule enforces a consistent style for void elements, which are elements that do not have closing tags (such as <img> or ). The first argument to the rule is the severity of the error, which is set to "error" in this case. The second argument is the expected style, which is set to "empty". This means that the element should not have a closing slash.

  • html/self-closing: This rule enforces a consistent style for self-closing elements, which are elements that have a slash before the closing angle bracket (such as <img / />). The first argument to the rule is the severity of the error, which is set to "error" in this case. The second argument is an object that specifies the expected style for different types of elements. In this example, the "html" key specifies the expected style for normal HTML elements and custom components. The "void" value is set to "always", which means that void elements should be self-closing. The "normal" value is set to "never", which means that normal HTML elements and custom components should not be self-closing. The "svg" and "math" keys specify the expected style for SVG and MathML elements, respectively, which should always be self-closing.

You can adjust these rules, or add new ones, to match your preferred HTML formatting style. The eslint-plugin-html plugin provides many other rules that you can use to enforce different aspects of HTML formatting, such as the use of specific attributes or the ordering of attributes within elements. You can find more information about these rules in the eslint-plugin-html documentation.

Example 1: Basic Configuration This configuration sets up ESLint to detect issues with HTML syntax and indentation:

{
"env": {
"browser": true
},
"plugins": [
"html"
],
"rules": {
"html/indent": "error",
"html/doctype-first": "error",
"html/no-trailing-whitespace": "error"
}
}
  • env: This sets the browser environment, which allows ESLint to recognize global variables and objects that are commonly used in web browsers.
  • plugins: This lists the plugins that we are using. In this case, we are only using the eslint-plugin-html plugin.
  • rules: This is where we configure the specific rules that we want to enable or modify. In this example, we are setting three rules:
    • html/indent: This rule enforces a consistent indentation for HTML code.
    • html/doctype-first: This rule ensures that the <!DOCTYPE html> declaration appears at the beginning of the HTML document.
    • html/no-trailing-whitespace: This rule ensures that there is no trailing whitespace at the end of an HTML line.

Example 2: Comprehensive Configuration This configuration sets up ESLint to detect issues with HTML syntax, indentation, attribute ordering, and more:

{
"env": {
"browser": true
},
"plugins": [
"html"
],
"rules": {
"html/indent": ["error", 2],
"html/doctype-first": "error",
"html/no-trailing-whitespace": "error",
"html/attribute-order": "error",
"html/attributes-order": ["error", {
"alphabetical": true,
"order": "longest-first"
}]
}
}
  • env: This sets the browser environment, which allows ESLint to recognize global variables and objects that are commonly used in web browsers.
  • plugins: This lists the plugins that we are using. In this case, we are only using the eslint-plugin-html plugin.
  • rules: This is where we configure the specific rules that we want to enable or modify. In this example, we are setting five rules:
    • html/indent: This rule enforces a consistent indentation for HTML code, with a value of 2 spaces.
    • html/doctype-first: This rule ensures that the <!DOCTYPE html> declaration appears at the beginning of the HTML document.
    • html/no-trailing-whitespace: This rule ensures that there is no trailing whitespace at the end of an HTML line.
    • html/attribute-order: This rule enforces a consistent ordering of attributes within HTML elements, based on the HTML specification.
    • html/attributes-order: This rule allows you to specify a custom order for HTML attributes. In this example, we are setting "alphabetical": true, which means that attributes should be sorted alphabetically within each group. We are also setting "order": "longest-first", which means that groups should be ordered with the longest group first.

Note that these are just two examples of configurations that you can use to . You can adjust these configurations, or add new rules, to match your preferred HTML formatting style and coding standards.

ESLint's eslint-plugin-html plugin provides the html/singleline-elements rule, which enforces a consistent style for HTML elements that are written on a single line. Here is an example .eslintrc.json configuration that includes this rule:

{
"plugins": [
"html"
],
"rules": {
"html/singleline-elements": ["error", {
"ignore": ["img", "input", "br", "hr", "area", "base", "col", "embed", "link", "meta", "param", "source", "track", "wbr"]
}]
}
}

In this example, the html/singleline-elements rule is set to "error", which means that ESLint will report an error if an HTML element is not written on a single line. The second argument is an object that specifies which elements to ignore, using an array of element names.

By default, the rule ignores certain elements that are commonly written on a single line in HTML, such as <img>, <input>, and . You can add or remove elements from the ignore array to customize the rule to your needs. For example, if you frequently write <span> elements on a single line, you could add "span" to the ignore array.

Here is an example of how this rule enforces the single-line style:

<!-- This will trigger an error because the <div> element is not written on a single line -->
<div class="my-class">Lorem ipsum dolor sit amet</div>

<!-- This will not trigger an error because the <span> element is ignored by the rule -->
<span class="my-class">Lorem ipsum dolor sit amet</span>

Note that this rule is just one of many available rules in the eslint-plugin-html plugin that you can use to enforce different aspects of HTML formatting. You can find more information about these rules in the eslint-plugin-html documentation.

eslint-plugin-html

using a tool like eslint-plugin-html along with ESLint to lint your HTML files, you can configure the plugin to handle HTML closing tags in a particular way.

The eslint-plugin-html plugin provides several rules for linting HTML files, including html-closing-tags, which enforces a specific style for closing tags. To configure this rule, you can add an entry for it in your .eslintrc file:

{
"plugins": [
"html"
],
"rules": {
"html/html-closing-tags": ["error", {
"singleline": "never",
"multiline": "always"
}]
}
}

In the above example, we are setting the html-closing-tags rule to throw an error if the closing tag style does not match the specified configuration. The singleline option specifies that closing tags should never be present on a single line, and the multiline option specifies that closing tags should always be on a separate line from the closing tag. You can adjust these options to match your preferred style.

Sure! Here's some more information about the html-closing-tags rule in eslint-plugin-html:

The html-closing-tags rule enforces a consistent style for closing tags in HTML files. It has several options that allow you to configure the expected style of the closing tags:

  • never - The closing tag should not be present on the same line as the end of the element.
  • always - The closing tag should always be on a separate line from the end of the element.
  • as-needed - The closing tag should be present on the same line as the end of the element if the element has no content, otherwise it should be on a separate line.

By default, html-closing-tags is set to { "singleline": "never", "multiline": "always" }, which means that closing tags should never be present on the same line as the end of the element on a single line, and should always be on a separate line if the element spans multiple lines.

To configure the html-closing-tags rule in your .eslintrc file, you can set the rule to an array with the first element being "error" to indicate that the rule should trigger an error if it is violated. The second element of the array should be an object containing the options you want to set for the rule. For example, to set the rule to "as-needed", you can use the following configuration:

{
"plugins": [
"html"
],
"rules": {
"html/html-closing-tags": ["error", {
"singleline": "as-needed",
"multiline": "as-needed"
}]
}
}

This configuration will trigger an error if any closing tags are not in the expected style, based on the "as-needed" option. You can adjust the options to match your preferred style.