Npm

Rules: правила проверки кода

В конфигурации примера выше мы использовали имеющиеся правила проверки. Но можно добавить и свои правила. В файле есть раздел rules.

Если при создании проекта указать не имеющийся набор инструкций, а задать свои правила (выбрав пункт Answer questins about your style), то в разделе правил в файле можно будет увидеть примерно такие правила:

'rules': {
        'indent': ,
        'linebreak-style': ,
        'quotes': ,
        'semi': 
    }

Структура правила проста. Рассмотрим первое правило из приведенного выше примера.

Слово — это имя правила. Первый элемент в списке обозначает уровень ошибки и может принимать следующие значения:

  • или 0 — выключить правило;
  • или 1 — включить правило как предупреждение (не влияет на код выхода);
  • или 2 — включить правило как ошибку (с кодом выхода 1).

Второй элемент в этом случае означает количество пробелов. Второй аргумент зависит от правила.

Итак, приведенные выше правила указывают, что следует использовать отступ в четыре пробела, завершение строк в стиле UNIX, одинарные кавычки и не пропускать точку с запятой.

Правила делятся на несколько категорий. Существуют правила проверки на наличие возможных синтаксических и логических ошибок в коде:

  • (обязательное применение оператора возврата в методах чтения);
  • (запрет применения оператора возврата в методах изменения значения);
  • (запрет дублирующихся аргументов в определениях функций).

Есть правила проверки соблюдения передовой практики, например, (обязательное применение пар методов чтения и изменения значений в объектах и классах).

Правила относительно переменных ( — запрет на неиспользуемые переменные), стилистические правила ( — разрешение или запрет символа новой строки в конце файла) и правила для ECMAScript 6.

Вернемся к коду, немного изменим файл и отправим его на проверку:

let i = 0
do {
    alert("Loop " + i);
    i++;

} while (true);

Будут выданы такие сообщения об ошибках:

Сообщения об ошибках

Здесь сообщается, что пропущена точка с запятой, используется отступ в два пробела вместо четырех и двойные кавычки вместо одинарных, а в цикле использовано константное условие.

Полный список правил ESLint можно просмотреть по этой ссылке.

Чтобы не вводить одни и те же команды каждый раз, можно в разделе  в файле указать сценарий для запуска . Он может выглядеть так:

"scripts": {

    "lint": "eslint . --fix"

  },

Вывод будет примерно таким:

Получим такие сообщения об ошибках

Эти сообщения об ошибках можно проигнорировать.

Проверку можно отключать как для отдельных строк, так и для нескольких.

Для отключения отдельной строки ее нужно завершить комментарием:

Чтобы отключить проверку для нескольких строк, перед ними следует вставить комментарий , а после — :

let i = 0;

do {

    alert('Loop ' + i);

    i++;

/* eslint-disable */

} while (true);

/* eslint-enable */

Также можно отключить одно или несколько конкретных правил. Для этого в комментарии их перечисляют через запятую:

extends​

You can extend an existing configuration (whether your own or a third-party one).

Popular configurations include:

  • stylelint-config-recommended — turns on just
  • stylelint-config-standard — extends recommended one by turning on 60

You’ll find more in .

When one configuration extends another, it starts with the other’s properties then adds to and overrides what’s there.

For example, you can extend the stylelint-config-standard and then change the indentation to tabs and turn off the rule:

Copy

You can extend an array of existing configurations, with each item in the array taking precedence over the previous item (so the second item overrides rules in the first, the third item overrides rules in the first and the second, and so on, the last item overrides everything else).

For example, with , then layer on top of that, and then override the indentation rule:

Copy

The value of is a «locater» (or an array of «locaters») that is ultimately d. It can fit whatever format works with Node’s algorithm. That means a «locater» can be:

  • the name of a module in (e.g. ; that module’s file must be a valid JSON configuration)
  • an absolute path to a file (which makes sense if you’re creating a JS object in a Node.js context and passing it in) with a or extension.
  • a relative path to a file with a or extension, relative to the referencing configuration (e.g. if configA has , we’ll look for relative to configA).

processors​

Processors are functions built by the community that hook into Stylelint’s pipeline, modifying code on its way into Stylelint and modifying results on their way out.

We discourage their use in favor of using the as processors are incompatible with the .

To use one, add a array to your config, containing «locaters» identifying the processors you want to use. As with , above, a «locater» can be either an npm module name, an absolute path, or a path relative to the invoking configuration file.

Copy

If your processor has options, make that item an array whose first item is the «locator» and second item is the options object.

Copy

Processors can also only be used with the CLI and the Node.js API, not with the PostCSS plugin. (The PostCSS plugin ignores them.)

Установка

Requirements

To install Next Active Directory Integration you need at least WordPress 5.6 and PHP 7.4

Although only tested with Apache 2.2 and 2.4 NADI should work with all other common web servers like nginx and IIS.

Next Active Directory Integration requires a few PHP modules to be enabled. Please verify in your that ldap and openssl are activated.

Important

As of 2021-12-09 NADI did no longer support PHP version < 7.4. The reason is that security support for PHP 7.3 and below has beeen dropped by the maintainers as you can see in the official PHP documentation http://php.net/supported-versions.php.
For security reasons and in order to use NADI in 2022 we hereby politely encourage you to migrate your environments to at least PHP 7.4 until then.

Thank you all for your support and understanding.

Best regards,
your NADI team.

Installation

NADI can be easily installed from the .

It is also possible to download the latest version from https://downloads.wordpress.org/plugin/next-active-directory-integration.zip» and unpack the folder to your wordpress/wp-content/plugins directory.

Developers can clone the Git Repository inside their wordpress/wp-content/plugins directory and download the dependencies with composer.

Single Site

  • Visit your WordPress blog and login into your WordPress dashboard as Administrator
  • Click on the Plugins in the left the navigation bar
  • Activate the Next Active Directory Integration plug-in

Network installation

  • Visit your WordPress network dashboard as Super Admin
  • Click on the Plugins link in the left the navigation bar
  • Activate the Next Active Directory Integration plug-in. In a WordPress network installation NADI should be Network activated.

Plugin developers

This plugin has a few extra functionality which you can use as a plugin developer.
However, if you use them, you should mention somewhere in your readme or install instructions that it needs to have all features available and so it won’t confuse your users if something is not working as described out-of-the-box because they don’t use this compose plugin yet.

You can specify in which phases your plugin should get executed within the object you return:

const{PHASE_DEVELOPMENT_SERVER}=require('next/constants');module.exports=(nextConfig={})=>{returnObject.assign({}, nextConfig,{    phasesPHASE_DEVELOPMENT_SERVER,webpack(config,options){if(typeofnextConfig.webpack==='function'){returnnextConfig.webpack(config, options);}return config;},};};

When a plugin gets loaded with , some additional information on which you can depend is available.
It gets passed in as the second argument to your plugin function:

module.exports=(nextConfig={},nextComposePlugins={})=>{console.log(nextComposePlugins);};

Currently, it contains these values:

{  nextComposePlugins boolean,  phase string,}

Using Configuration Files

There are two ways to use configuration files.

The first way to use configuration files is via and files. ESLint will automatically look for them in the directory of the file to be linted, and in successive parent directories all the way up to the root directory of the filesystem (unless is specified). Configuration files can be useful when you want different configurations for different parts of a project or when you want others to be able to use ESLint directly without needing to remember to pass in the configuration file.

The second way to use configuration files is to save the file wherever you would like and pass its location to the CLI using the option, such as:

If you are using one configuration file and want ESLint to ignore any files, make sure to use along with the flag.

Here’s an example JSON configuration file that uses the parser to support TypeScript syntax:

Both the JSON and YAML configuration file formats support comments (package.json files should not include them). You can use JavaScript-style comments for JSON files and YAML-style comments for YAML files. ESLint safely ignores comments in configuration files. This allows your configuration files to be more human-friendly.

For JavaScript-style comments:

For YAML-style comments:

Rule Details

Examples of incorrect code for this rule:

class Hello extends React.Component {
  render() {
    return <div>Hello Bob<div>;
  }
});

Hello.propTypes = {
  name: PropTypes.string
},
type Props = {
  firstname: string,
  middlename: string, // middlename is never used by the Hello component
  lastname: string
}

class Hello extends React.Component<Props> {
  render() {
    return <div>Hello {this.props.firstname} {this.props.lastname}<div>;
  }
}
type Props = {
  firstname: string;
  lastname: string;  // lastname isn't used by the Hello component
};

class Hello extends React.Component<Props> {
  render() {
    return <div>Hello {this.props.firstname}<div>;
  }
}

class Greetings extends React.Component<Props> {
  render() {
    return <div>Greetings  {this.props.firstname} {this.props.lastname}<div>;
  }
}

Examples of correct code for this rule:

class Hello extends React.Component {
  render() {
    return <div>Hello {this.props.name}<div>;
  }
};

Hello.propTypes: {
  name: PropTypes.string
},

Usage

// next.config.js
const withPlugins = require('next-compose-plugins');

module.exports = withPlugins(...plugins, nextConfiguration);

It is an array containing all plugins and their configuration.
If a plugin does not need additional configuration, you can simply add the imported plugin.
If it does need configuration or you only want to run it in a specific phase, you can specify an array:

Imported plugin.
See the section if you only want to require a plugin when it is really used.

const withPlugins = require('next-compose-plugins');
const sass = require('@zeit/next-sass');

module.exports = withPlugins(
  sass,
);

Configuration for the plugin.

You can also overwrite specific configuration keys for a phase:

const withPlugins = require('next-compose-plugins');
const { PHASE_PRODUCTION_BUILD } = require('next/constants');
const sass = require('@zeit/next-sass');

module.exports = withPlugins(
  sass, {
    cssModules: true,
    cssLoaderOptions: {
      localIdentName: '______',
    },
    PHASE_PRODUCTION_BUILD: {
      cssLoaderOptions: {
        localIdentName: '',
      },
    },
  },
);

This will overwrite the with the new specified, but only during production build.
You can also combine multiple phases () or exclude a phase ( which will overwrite the config in all phases except ).
You can use all phases .

If the plugin should only be applied in specific phases, you can specify them here.
You can use all phases .

const withPlugins = require('next-compose-plugins');
const { PHASE_DEVELOPMENT_SERVER, PHASE_PRODUCTION_BUILD } = require('next/constants');
const sass = require('@zeit/next-sass');

module.exports = withPlugins(
  sass, {
    cssModules: true,
    cssLoaderOptions: {
      localIdentName: '______',
    },
  }, PHASE_DEVELOPMENT_SERVER, PHASE_PRODUCTION_BUILD,
);

You can also negate the phases with a leading :

const withPlugins = require('next-compose-plugins');
const { PHASE_DEVELOPMENT_SERVER, PHASE_PRODUCTION_BUILD } = require('next/constants');
const sass = require('@zeit/next-sass');

module.exports = withPlugins(
  sass, {
    cssModules: true,
    cssLoaderOptions: {
      localIdentName: '______',
    },
  }, '!', PHASE_DEVELOPMENT_SERVER,
);

This will apply the plugin in all phases except .

Any direct can go here, for example: .

You can also customize the webpack configuration of next.js within this object.

const withPlugins = require('next-compose-plugins');

const nextConfig = {
  distDir: 'build',
  webpack: (config, options) => {

    // modify the `config` here

    return config;
  },
};

module.exports = withPlugins(
  // add plugins here..
, nextConfig);

Phases are also supported within the object and have the same syntax as in .

const { PHASE_DEVELOPMENT_SERVER } = require('next/constants');
const nextConfig = {
  distDir: 'build',
  '!' + PHASE_DEVELOPMENT_SERVER: {
    assetPrefix: 'https://my.cdn.com',
  },
};

Optional plugins

If a plugin should only get loaded when it is used, you can use the helper function.
This can especially be useful if the plugin is only in the and so may not be available in all phases.
If you don’t use the helper in this case, you would get an error.

const { withPlugins, optional } = require('next-compose-plugins');
const { PHASE_DEVELOPMENT_SERVER } = require('next/constants');

module.exports = withPlugins(
  optional(() => require('@zeit/next-sass')), { /* optional configuration */ }, PHASE_DEVELOPMENT_SERVER,
);

Extend another config file

It sometimes makes sense to split a file into multiple files, for example when you have more than just one next.js project in one repository.
You can then define the base config in one file and add project specific plugins/settings in the config file or the project.

To easily archive this, you can use the helper in the file of your project.

// next.config.js
const { withPlugins, extend } = require('next-compose-plugins');
const baseConfig = require('./base.next.config.js');

const nextConfig = { /* ... */ };

module.exports = extend(baseConfig).withPlugins(
  sass, {
    cssModules: true,
  },
, nextConfig);
// base.next.config.js
const withPlugins = require('next-compose-plugins');

module.exports = withPlugins(
  typescript, {
    typescriptLoaderOptions: {
      transpileOnly: false,
    },
  },
);

Recap

Let’s now recap what we learned line by line and check our understanding.

  • Line 1: We import the Hook from React. It lets us keep local state in a function component.
  • Line 4: Inside the component, we declare a new state variable by calling the Hook. It returns a pair of values, to which we give names. We’re calling our variable because it holds the number of button clicks. We initialize it to zero by passing as the only argument. The second returned item is itself a function. It lets us update the so we’ll name it .
  • Line 9: When the user clicks, we call with a new value. React will then re-render the component, passing the new value to it.

This might seem like a lot to take in at first. Don’t rush it! If you’re lost in the explanation, look at the code above again and try to read it from top to bottom. We promise that once you try to “forget” how state works in classes, and look at this code with fresh eyes, it will make sense.

Tip: What Do Square Brackets Mean?

You might have noticed the square brackets when we declare a state variable:

The names on the left aren’t a part of the React API. You can name your own state variables:

This JavaScript syntax is called . It means that we’re making two new variables and , where is set to the first value returned by , and is the second. It is equivalent to this code:

When we declare a state variable with , it returns a pair — an array with two items. The first item is the current value, and the second is a function that lets us update it. Using and to access them is a bit confusing because they have a specific meaning. This is why we use array destructuring instead.

Tip: Using Multiple State Variables

Declaring state variables as a pair of is also handy because it lets us give different names to different state variables if we want to use more than one:

In the above component, we have , , and as local variables, and we can update them individually:

You don’t have to use many state variables. State variables can hold objects and arrays just fine, so you can still group related data together. However, unlike in a class, updating a state variable always replaces it instead of merging it.

We provide more recommendations on splitting independent state variables .

Cascading and Hierarchy

When using and files for configuration, you can take advantage of configuration cascading. Suppose you have the following structure:

The configuration cascade works based on the location of the file being linted. If there is a file in the same directory as the file being linted, then that configuration takes precedence. ESLint then searches up the directory structure, merging any files it finds along the way until reaching either a file with or the root directory.

In the same way, if there is a file in the root directory with an field, the configuration it describes will apply to all subdirectories beneath it, but the configuration described by the file in the directory will override it where there are conflicting specifications.

If there is an and a file found in the same directory, will take priority and file will not be used.

By default, ESLint will look for configuration files in all parent folders up to the root directory. This can be useful if you want all of your projects to follow a certain convention, but can sometimes lead to unexpected results. To limit ESLint to a specific project, place inside the file or field of the file or in the file at your project’s root level. ESLint will stop looking in parent folders once it finds a configuration with .

And in YAML:

For example, consider which has set in the file in the directory. In this case, while linting , the configurations within will be used, but the file in will not.

The complete configuration hierarchy, from highest to lowest precedence, is as follows:

  1. Inline configuration
    1. and
  2. Command line options (or CLIEngine equivalents):
    1. ,
  3. Project-level configuration:
    1. or file in the same directory as the linted file
    2. Continue searching for and files in ancestor directories up to and including the root directory or until a config with is found.

Usage

constwithPlugins=require('next-compose-plugins');module.exports=withPlugins(...plugins, nextConfiguration);

It is an array containing all plugins and their configuration.
If a plugin does not need additional configuration, you can simply add the imported plugin.
If it does need configuration or you only want to run it in a specific phase, you can specify an array:

constwithPlugins=require('next-compose-plugins');constsass=require('@zeit/next-sass');module.exports=withPlugins(sass,);

Configuration for the plugin.

You can also overwrite specific configuration keys for a phase:

constwithPlugins=require('next-compose-plugins');const{PHASE_PRODUCTION_BUILD}=require('next/constants');constsass=require('@zeit/next-sass');module.exports=withPlugins(sass,{    cssModulestrue,    cssLoaderOptions{      localIdentName'______',},PHASE_PRODUCTION_BUILD{      cssLoaderOptions{        localIdentName'',},},},);
constwithPlugins=require('next-compose-plugins');const{PHASE_DEVELOPMENT_SERVER,PHASE_PRODUCTION_BUILD}=require('next/constants');constsass=require('@zeit/next-sass');module.exports=withPlugins(sass,{    cssModulestrue,    cssLoaderOptions{      localIdentName'______',},},PHASE_DEVELOPMENT_SERVER,PHASE_PRODUCTION_BUILD,);

You can also negate the phases with a leading :

constwithPlugins=require('next-compose-plugins');const{PHASE_DEVELOPMENT_SERVER,PHASE_PRODUCTION_BUILD}=require('next/constants');constsass=require('@zeit/next-sass');module.exports=withPlugins(sass,{    cssModulestrue,    cssLoaderOptions{      localIdentName'______',},},'!',PHASE_DEVELOPMENT_SERVER,);

This will apply the plugin in all phases except .

You can also customize the webpack configuration of next.js within this object.

constwithPlugins=require('next-compose-plugins');constnextConfig={  distDir'build',webpack(config,options)=>{return config;},};module.exports=withPlugins(, nextConfig);
const{PHASE_DEVELOPMENT_SERVER}=require('next/constants');constnextConfig={  distDir'build','!'+PHASE_DEVELOPMENT_SERVER{    assetPrefix'https://my.cdn.com',},};

If a plugin should only get loaded when it is used, you can use the helper function.
This can especially be useful if the plugin is only in the and so may not be available in all phases.
If you don’t use the helper in this case, you would get an error.

const{withPlugins,optional}=require('next-compose-plugins');const{PHASE_DEVELOPMENT_SERVER}=require('next/constants');module.exports=withPlugins(optional(()=>require('@zeit/next-sass')),{},PHASE_DEVELOPMENT_SERVER,);

It sometimes makes sense to split a file into multiple files, for example when you have more than just one next.js project in one repository.
You can then define the base config in one file and add project specific plugins/settings in the config file or the project.

To easily archive this, you can use the helper in the file of your project.

const{withPlugins,extend}=require('next-compose-plugins');constbaseConfig=require('./base.next.config.js');constnextConfig={};module.exports=extend(baseConfig).withPlugins(sass,{    cssModulestrue,},, nextConfig);
constwithPlugins=require('next-compose-plugins');module.exports=withPlugins(typescript,{    typescriptLoaderOptions{      transpileOnlyfalse,},},);

Use

Add plugin to a config file (.eslintrc) and make it default processor:

{
  "plugins": ,
  "processor": "disable/disable"
}

Inline comments

Regular disable

Plugin adds a custom directive to use in files in a form of inline comment, which allows to disable entire plugins for this file. Plugin names have to be the same as in ESLint config file, separated by comma.

The following directive will disable «react» and «jsx-a11y» plugins for this particular file.

/* eslint-plugin-disable react, jsx-a11y */

function greet(name) {
  console.log('Hi, ' + name);
}

If no any plugins provided — all plugins registered in ESLint config will be disabled:

/* eslint-plugin-disable */

function greet(name) {
  console.log('Hi, ' + name);
}
Disable all except

Another custom option allows to disable all plugins except ones that are specified. It might be useful when there are a lot of plugins in the project and it is required to use one or two of them for particular files, usage of regular disable syntax might be cumbersome to maintain if there are plans to add new plugins to the project. Plugin names have to be the same as in ESLint config file, separated by comma.

The following directive will disable all plugins registered in ESLint config except «react» and «jsx-a11y».

/* eslint-plugin-disable-all-except react, jsx-a11y */

function greet(name) {
  console.log('Hi, ' + name);
}

Notes:

  • disable all except: if no plugins specified, then none of the plugins listed in ESLint config will be disabled i.e. error messages will not be removed from ESLint report
  • whitespace inside block comment is ignored
  • original file is not modified
  • there is no way to restore behavior with another inline option
Regular disable

The following config will:

  • disable «import» and «jsx-a11y» plugins for all files matching «tests/**/*.test.js» glob pattern
  • disable «react» plugin for all files matching «lib/*.js» glob pattern
{
  "plugins": ,
  "processor": "disable/disable",
  "overrides": [
    {
      "files": ["tests/**/*.test.js"],
      "settings": {
        "disable/plugins": 
      }
    },
    {
      "files": ["lib/*.js"],
      "settings": {
        "disable/plugins": 
      }
    }
  ]
}

To disable all registered plugins you can simply omit «disable/plugins» setting or use a star in place of plugin name:

{
  "plugins": ,
  "processor": "disable/disable",
  "overrides": [
    {
      "files": ["tests/**/*.test.js"],
      "settings": {
        "disable/plugins": "*"
      }
    }
  ]
}
Disable all except

To disable all plugins except specified ones use «disableAllExcept» flag in config settings (.eslintrc).

The following config will disable all registered plugins except «react» for all files mathing «tests/**/*.test.js» glob pattern («import» and «jsx-a11y» will be disabled).

{
  "plugins": ,
  "processor": "disable/disable",
  "overrides": [
    {
      "files": ["tests/**/*.test.js"],
      "settings": {
        "disable/disableAllExcept": true,
        "disable/plugins": 
      }
    }
  ]
}

JSX-specific rules

Rule Description
react/jsx-boolean-value Enforce boolean attributes notation in JSX
react/jsx-child-element-spacing Ensures inline tags are not rendered without spaces between them
react/jsx-closing-bracket-location Validate closing bracket location in JSX
react/jsx-closing-tag-location Validate closing tag location for multiline JSX
react/jsx-curly-brace-presence Disallow unnecessary JSX expressions when literals alone are sufficient or enfore JSX expressions on literals in JSX children or attributes
react/jsx-curly-newline Enforce consistent line breaks inside jsx curly
react/jsx-curly-spacing Enforce or disallow spaces inside of curly braces in JSX attributes
react/jsx-equals-spacing Disallow or enforce spaces around equal signs in JSX attributes
react/jsx-filename-extension Restrict file extensions that may contain JSX
react/jsx-first-prop-new-line Ensure proper position of the first property in JSX
react/jsx-fragments Enforce shorthand or standard form for React fragments
react/jsx-handler-names Enforce event handler naming conventions in JSX
react/jsx-indent Validate JSX indentation
react/jsx-indent-props Validate props indentation in JSX
react/jsx-key Report missing props in iterators/collection literals
react/jsx-max-depth Validate JSX maximum depth
react/jsx-max-props-per-line Limit maximum of props on a single line in JSX
react/jsx-newline Require or prevent a new line after jsx elements and expressions.
react/jsx-no-bind Prevents usage of Function.prototype.bind and arrow functions in React component props
react/jsx-no-comment-textnodes Comments inside children section of tag should be placed inside braces
react/jsx-no-constructed-context-values Prevents JSX context provider values from taking values that will cause needless rerenders.
react/jsx-no-duplicate-props Enforce no duplicate props
react/jsx-no-literals Prevent using string literals in React component definition
react/jsx-no-script-url Forbid URLs
react/jsx-no-target-blank Forbid attribute without
react/jsx-no-undef Disallow undeclared variables in JSX
react/jsx-no-useless-fragment Disallow unnecessary fragments
react/jsx-one-expression-per-line Limit to one expression per line in JSX
react/jsx-pascal-case Enforce PascalCase for user-defined JSX components
react/jsx-props-no-multi-spaces Disallow multiple spaces between inline JSX props
react/jsx-props-no-spreading Prevent JSX prop spreading
react/jsx-sort-default-props Enforce default props alphabetical sorting
react/jsx-sort-props Enforce props alphabetical sorting
react/jsx-space-before-closing Validate spacing before closing bracket in JSX
react/jsx-tag-spacing Validate whitespace in and around the JSX opening and closing brackets
react/jsx-uses-react Prevent React to be marked as unused
react/jsx-uses-vars Prevent variables used in JSX to be marked as unused
react/jsx-wrap-multilines Prevent missing parentheses around multilines JSX

Extending Configuration Files

A configuration file, once extended, can inherit all the traits of another configuration file (including rules, plugins, and language options) and modify all the options. As a result, there are three configurations, as defined below:

  • Base config: the configuration that is extended.
  • Derived config: the configuration that extends the base configuration.
  • Resulting actual config: the result of merging the derived configuration into the base configuration.

The property value is either:

  • a string that specifies a configuration (either a path to a config file, the name of a shareable config, , or )
  • an array of strings where each additional configuration extends the preceding configurations

ESLint extends configurations recursively, so a base configuration can also have an property. Relative paths and shareable config names in an property are resolved from the location of the config file where they appear.

The prefix can be omitted from the configuration name. For example, resolves as .

The property can do any of the following to extend (or override) the set of rules:

  • enable additional rules
  • change an inherited rule’s severity without changing its options:
    • Base config:
    • Derived config:
    • Resulting actual config:
  • override options for rules from base configurations:
    • Base config:
    • Derived config:
    • Resulting actual config:
  • override options for rules given as object from base configurations:
    • Base config:
    • Derived config:
    • Resulting actual config: where and default to

Using a shareable configuration package

A sharable configuration is an npm package that exports a configuration object. Make sure that you have installed the package in your project root directory, so that ESLint can require it.

The property value can omit the prefix of the package name.

The command can create a configuration so you can extend a popular style guide (for example, ).

Example of a configuration file in YAML format:

Using

Using in the property enables a subset of core rules that report common problems (these rules are identified with a checkmark ✓ on the rules page).

Here’s an example of extending and overriding some of the set configuration options:

Example of a configuration file in JavaScript format:

Using a configuration from a plugin

A plugin is an npm package that can add various extensions to ESLint. A plugin can perform numerous functions, including but not limited to adding new rules and exporting . Make sure the package has been installed in a directory where ESLint can require it.

The can omit the prefix of the package name.

The property value can consist of:

  • the package name (from which you can omit the prefix, for example, is short for )
  • the configuration name (for example, )

Example of a configuration file in JSON format:

Using a configuration file

The property value can be an absolute or relative path to a base . ESLint resolves a relative path to a base configuration file relative to the configuration file that uses it.

Example of a configuration file in JSON format:

Using

The property value can be to enable all core rules in the currently installed version of ESLint. The set of core rules can change at any minor or major version of ESLint.

Important: This configuration is not recommended for production use because it changes with every minor and major version of ESLint. Use it at your own risk.

You might enable all core rules as a shortcut to explore rules and options while you decide on the configuration for a project, especially if you rarely override options or disable rules. The default options for rules are not endorsements by ESLint (for example, the default option for the rule does not mean double quotes are better than single quotes).

If your configuration extends , after you upgrade to a newer major or minor version of ESLint, review the reported problems before you use the option on the , so you know if a new fixable rule will make changes to the code.

Example of a configuration file in JavaScript format:

Рейтинг
( Пока оценок нет )
Понравилась статья? Поделиться с друзьями:
Все про сервера
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: