# ESLint Plugin Light

Simple Eslint plugin.

# 1. Installation

You need to install ESLint (opens new window) first.

npm i eslint -D

Next, install eslint-plugin-light.

npm i eslint-plugin-light -D

# 2. Usage

Add light to the plugins section of your .eslintrc configuration file. You can omit the eslint-plugin- prefix:

{
    "plugins": [
        "light"
    ]
}

Then configure the rules you want to use under the rules section.

{
    "rules": {
        "light/rule-name": 2
    }
}

or use extends:

{
  "extends": ["plugin:light/recommended"],
}

# 3. Supported Rules

# 3.1. light/valid-vue-comp-import

禁止从js文件中加载Vue组件

比如,

  1. 导入地址是js/ts文件
import SomeComp from 'src/local-component/ui/pages/user/account-manage/index.js';

// 或者省略了js/ts文件后缀
import SomeComp from 'src/local-component/ui/pages/user/account-manage/index';

如果加了 --fix,会被转换为:

import SomeComp from 'src/local-component/ui/pages/user/account-manage/xxx.vue';

注意上面的xxx.vue是从index.js中分析得到的原始文件路径。

  1. 导入一个目录,但目录存在index.js,这时候不管存不存在index.vueuni-app转换都会失败
import SomeComp from 'src/local-component/ui/pages/user/account-manage';

可转换为:

import SomeComp from 'src/local-component/ui/pages/user/account-manage/xxx.vue';
  1. 具名导入
import {
  AComp,
  BComp,
  CComp,
  DComp,
} from './comp';

可转换为:

import AComp from 'src/local-component/module/tip-match/tip-match-schedule-tree-new/comp/a.vue';
import BComp from 'src/local-component/module/tip-match/tip-match-schedule-tree-new/comp/b.vue';
import CComp from 'src/local-component/module/tip-match/tip-match-schedule-tree-new/comp/c.vue';
import DComp from 'src/local-component/module/tip-match/tip-match-schedule-tree-new/comp/d.vue';

# 3.2. light/no-plus-turn-number

禁止在vuetemplate中用+号转换字符串为数字

比如:

<ScheduleItem
  :child-id="+childId"
/>

如果加了--fix,会被转化成:

<ScheduleItem
  :child-id="parseInt(childId, 10)"
/>

# 3.3 no-complex-key

不要在vue模板中使用复杂的key。包括:

  1. 字符串拼接,如:
:key="`hold` + index"`
  1. 模板字符串,如:
:key="`hold-${index}`"
  1. key提到一个函数中,如:
:key="getHoldKey(index)"

getHoldKey(index) {
  return `hold${index}`
}

最佳方式其实是提前处理好数据,这样性能会更好,也避免了key重复。

getData() {
  items = items.map((item,index) => ({
    ...item,
    key: `hold-${index}`
  }))
}

uni-app中,key重复的话,会造成挂载在组件上面的事件参数为undefined,从而不成功。

# 3.4 json-parse-try-catch

JSON.parse 应该加 try catch

默认配置会排除下面情况:

JSON.parse(JSON.stringify(abc));

可以配置 strict 参数为 true,开启检查。

// .eslintrc.js

module.exports = {
  plugins: [
    'light',
  ],
  rules: {
    'light/json-parse-try-catch': [2, { strict: true }],
  },
}
Last Updated: 2025/3/29 16:32:34