亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
2. Write a Basic Custom Rule
3. Test Your Custom Rule
4. Use Advanced AST Patterns
5. Make Rules Configurable and Reusable
首頁 web前端 js教程 為您的項(xiàng)目創(chuàng)建自定義ESLINT規(guī)則

為您的項(xiàng)目創(chuàng)建自定義ESLINT規(guī)則

Jul 25, 2025 am 12:30 AM
eslint 規(guī)則

創(chuàng)建自定義ESLint規(guī)則需先建立規(guī)則目錄並配置.eslintrc.js通過require或本地插件方式加載;2. 編寫規(guī)則需定義meta和create函數(shù),通過AST遍歷檢查代碼模式,如禁止特定路徑導(dǎo)入;3. 使用eslint-rule-tester編寫測試用例,確保規(guī)則在有效和無效代碼中行為正確;4. 利用AST深度分析實(shí)現(xiàn)高級功能,如限制函數(shù)調(diào)用、命名規(guī)範(fàn)或環(huán)境變量訪問;5. 通過schema配置使規(guī)則可複用,並支持跨項(xiàng)目共享於私有npm包或monorepo中,最終實(shí)現(xiàn)團(tuán)隊(duì)編碼規(guī)範(fàn)的自動化enforcement。

Creating Custom ESLint Rules for Your Project

If you're working on a JavaScript or TypeScript project with specific coding standards that existing ESLint rules don't fully cover, creating custom ESLint rules is a powerful way to enforce your team's best practices. While ESLint comes with a rich set of built-in rules and plugins, sometimes you need something tailored—like banning certain function calls, enforcing naming patterns, or validating file structure.

Creating Custom ESLint Rules for Your Project

Here's how to create and use custom ESLint rules in your project effectively.


1. Set Up a Custom Rule Directory

Start by organizing your custom rules. ESLint allows you to define rules locally in your project using a plugin-like structure.

Creating Custom ESLint Rules for Your Project

Create a directory for your rules, eg:

 mkdir -p .eslint/rules

Then, make sure your ESLint configuration can find them. You don't need to publish a full plugin—just use ESLint's rules object directly or load them via a plugin path.

Creating Custom ESLint Rules for Your Project

In .eslintrc.js , you can load rules using require :

 const myCustomRule = require('./.eslint/rules/no-internal-import');

module.exports = {
  rules: {
    'no-internal-import': ['error', { disallowedPaths: ['src/utils/internal'] }],
  },
  // ... other config
};

Alternatively, define a local plugin:

 plugins: {
  'my-rules': {
    rules: {
      'no-internal-import': myCustomRule,
    },
  },
},
rules: {
  'my-rules/no-internal-import': 'error',
}

2. Write a Basic Custom Rule

A rule is an object with a meta property and a create function that defines behavior during AST traversal.

Let's create a rule that prevents imports from internal utility folders unless explicitly allowed.

.eslint/rules/no-internal-import.js

 module.exports = {
  meta: {
    type: 'suggestion',
    docs: {
      description: 'disallow imports from internal utility folders',
    },
    schema: [
      {
        type: 'object',
        properties: {
          disallowedPaths: {
            type: 'array',
            items: { type: 'string' },
          },
        },
        additionalProperties: false,
      },
    ],
  },

  create(context) {
    const options = context.options[0] || {};
    const disallowedPaths = options.disallowedPaths || [];

    return {
      ImportDeclaration(node) {
        const importPath = node.source.value;

        for (const path of disallowedPaths) {
          if (importPath.startsWith(path)) {
            context.report({
              node,
              message: `Import from disallowed path: ${path}`,
            });
          }
        }
      },
    };
  },
};

This rule checks every import statement and warns if it starts with a path in the disallowedPaths list.


3. Test Your Custom Rule

Testing ensures your rule behaves correctly and doesn't break with edge cases.

Use ESLint's testing tools:

 npm install eslint eslint-plugin-node eslint-rule-tester --save-dev

Create a test file: .eslint/rules/__tests__/no-internal-import.test.js

 const { RuleTester } = require('eslint');
const rule = require('../no-internal-import');

const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 2021, sourceType: 'module' } });

ruleTester.run('no-internal-import', rule, {
  valid: [
    "import { util } from 'src/utils/public';",
    { code: "import { util } from 'src/helpers';", options: [{ disallowedPaths: ['src/utils/internal'] }] },
  ],
  invalid: [
    {
      code: "import internal from 'src/utils/internal/helper';",
      errors: [{ message: "Import from disallowed path: src/utils/internal" }],
    },
  ],
});

Run the test via a script in package.json :

 "scripts": {
  "test:eslint": "node .eslint/rules/__tests__/no-internal-import.test.js"
}

4. Use Advanced AST Patterns

Custom rules shine when you need deep code analysis. For example:

  • Enforce function call restrictions: ban console.log in production files.
  • Validate naming conventions: component files must end in .tsx if they export a React component.
  • Check for side effects: prevent direct access to environment variables outside config files.

Example: ban process.env outside allowed files.

 MemberExpression(node) {
  if (
    node.object.type === 'Identifier' &&
    node.object.name === 'process' &&
    node.property.name === 'env' &&
    !context.getFilename().includes('config/')
  ) {
    context.report({
      node,
      message: 'Direct access to process.env is only allowed in config files.',
    });
  }
}

You can access file paths, comments, and even scope information via context .


5. Make Rules Configurable and Reusable

Good custom rules are flexible. Use the schema in meta to allow options:

 schema: [
  {
    type: 'object',
    properties: {
      exemptFiles: { type: 'array', items: { type: 'string' } },
    },
  },
],

Then check context.getFilename() in your logic to apply exemptions.

Also, consider sharing rules across projects by packaging them in a private npm module or monorepo package.


Creating custom ESLint rules isn't hard once you understand the AST and ESLint's plugin model. Start small—ban a pattern you see often—then expand as needed. The payoff is cleaner, more consistent code with automated enforcement.

Basically, if your team keeps making the same mistake in code reviews, it's probably time to write a rule for it.

以上是為您的項(xiàng)目創(chuàng)建自定義ESLINT規(guī)則的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Laravel 教程
1597
29
PHP教程
1488
72
react怎麼刪除eslint react怎麼刪除eslint Dec 30, 2022 am 09:46 AM

react刪除eslint的方法:1、執(zhí)行「npm run eject」指令;2、在package.json中修改程式碼為「 "eslintConfig": {"extends": ["react-app","re??act-app/jest" ],"rules": {"no-undef": "off"...}」;3、重啟項(xiàng)目即可。

PHP函數(shù)的命名規(guī)範(fàn)及規(guī)則 PHP函數(shù)的命名規(guī)範(fàn)及規(guī)則 May 19, 2023 am 08:14 AM

PHP作為一種非常流行的腳本語言,有著強(qiáng)大的函數(shù)庫支持,其函數(shù)的命名規(guī)範(fàn)和規(guī)則對於開發(fā)效率和程式碼可讀性都有著重要的影響。本文將介紹PHP函數(shù)的命名規(guī)範(fàn)及規(guī)則。一、命名風(fēng)格在PHP中,函數(shù)名稱需要嚴(yán)格符合命名規(guī)範(fàn)和規(guī)則,規(guī)範(fàn)主要包括兩個(gè)面向:命名風(fēng)格和命名規(guī)則。 1.下劃線命名法底線命名法是PHP函數(shù)命名最常用的方式,也是官方推薦的一種方式。遵循這種方式的函數(shù)名

指標(biāo)比較的規(guī)則和例外? 指標(biāo)比較的規(guī)則和例外? Jun 04, 2024 pm 06:01 PM

在C/C++中,指標(biāo)比較規(guī)則如下:指向同一物件的指標(biāo)相等。指向不同物件的指標(biāo)不相等。例外:指向空位址的指標(biāo)相等。

工具分享:實(shí)現(xiàn)前端埋點(diǎn)的自動化管理 工具分享:實(shí)現(xiàn)前端埋點(diǎn)的自動化管理 Dec 07, 2022 pm 04:14 PM

埋點(diǎn)一直是 H5 專案中的重要一環(huán),而埋點(diǎn)資料更是後期改善業(yè)務(wù)和技術(shù)優(yōu)化的重要基礎(chǔ)。在日常的工作中,常常會有產(chǎn)品或業(yè)務(wù)的同學(xué)來問,「這個(gè)專案現(xiàn)在有哪些埋點(diǎn)?」,「這個(gè)埋點(diǎn)用在哪些地方?」像這樣的問題基本上都是問一次查一次程式碼,效率很低。

深入探索Python標(biāo)識符的定義與規(guī)範(fàn) 深入探索Python標(biāo)識符的定義與規(guī)範(fàn) Dec 29, 2023 am 08:34 AM

深入了解Python標(biāo)識符的定義與規(guī)則,需要具體程式碼範(fàn)例Python是一種簡潔而強(qiáng)大的程式語言,具有廣泛的應(yīng)用領(lǐng)域。在Python編程中,標(biāo)識符起著至關(guān)重要的作用。本文將深入探討Python標(biāo)識符的定義與規(guī)則,並提供具體的程式碼範(fàn)例,幫助讀者更好地理解與應(yīng)用。首先,我們來了解一下Python標(biāo)識符的定義。在Python中,標(biāo)識符可以是變數(shù)、函數(shù)、類別、模組等的名

Linux防火牆之-iptables詳解 Linux防火牆之-iptables詳解 Feb 20, 2024 am 11:57 AM

專案介紹iptables是Linux系統(tǒng)下的免費(fèi)包過濾防火牆軟體,可實(shí)現(xiàn)封包過濾、封包重定向和網(wǎng)路位址轉(zhuǎn)換等功能。它是一個(gè)高效且靈活的解決方案,可取代昂貴的商業(yè)防火牆。 iptables具有強(qiáng)大的配置選項(xiàng)和規(guī)則設(shè)置,使用戶能夠根據(jù)自身需求對網(wǎng)路流量進(jìn)行精細(xì)控制,提高網(wǎng)路安全性和效能。 iptables的規(guī)則其實(shí)是指網(wǎng)路管理員預(yù)先定義的條件,則規(guī)則一般的定義為「如果封包頭符合這樣的條件,就這樣處理這個(gè)封包」。規(guī)則儲存在核心空間的資訊包過濾表中,這些規(guī)則分別指定了來源位址、目的位址、傳輸協(xié)定(如TCP、U

Vue-cli中使用ESLint進(jìn)行程式碼規(guī)範(fàn)化和bug偵測 Vue-cli中使用ESLint進(jìn)行程式碼規(guī)範(fàn)化和bug偵測 Jun 09, 2023 pm 04:13 PM

隨著前端技術(shù)的不斷發(fā)展,我們面臨的問題也逐漸複雜了起來,不僅要求我們的程式碼結(jié)構(gòu)合理、模組化設(shè)計(jì)良好,更需要程式碼的可維護(hù)性和執(zhí)行效率。在這個(gè)過程中,如何保證程式碼的品質(zhì)和規(guī)範(fàn)性成為了一個(gè)難題。萬幸的是,程式碼規(guī)範(fàn)化和bug檢測工具的出現(xiàn),為我們提供了有效的解決方案。而在Vue.js框架中使用ESLint進(jìn)行程式碼規(guī)範(fàn)化和bug偵測已成為一種普遍選擇。一、ESLint

彈性佈局的規(guī)則包括哪些 彈性佈局的規(guī)則包括哪些 Nov 21, 2023 pm 01:33 PM

彈性佈局的規(guī)則包括:1、容器和項(xiàng)目的聲明;2、主軸和交叉軸;3、對齊和分佈;4、彈性項(xiàng)目的屬性;5、換行和反向;6、空間分佈和大小調(diào)整;7 、交叉軸順序;8、交叉軸對齊;9、彈性容器的額外規(guī)則;10、嵌套彈性容器等。詳細(xì)介紹:1、容器和項(xiàng)目的聲明,在彈性佈局中,容器用於包含項(xiàng)目,容器可以是任何塊級元素;2、主軸和交叉軸,彈性佈局中的項(xiàng)目被排列在主軸和交叉軸上;3、對齊和分佈等等。

See all articles