import顺序优化
1. 规范定义
建议将 import
语句按照以下层次进行分类和排序:
第一梯队:框架核心(如 React)。
第二梯队:第三方库(如 antd)。
第三梯队:项目内部模块(如服务层代码)。
第四梯队:同级组件(如本地组件)。
示例代码:
import React, { useState, useEffect } from 'react';
import { Spin } from 'antd';
import { useRouter } from 'react-router-dom';
import { getMockDataList } from '@/service/testCenter';
import testIcon from "@/images/test/testIcon.svg";
import styles from './index.module.scss';
import ComponentA from "../components/ComponentA";
import ComponentB from "../components/ComponentB";
import ComponentC from "../components/ComponentC";
2. 自动化校验(上手段)
通过 ESLint 配置来自动校验 import
的顺序。关键配置如下:
{
"rules": {
"import/order": [
"error",
{
"groups": [
"builtin", // Node内置
"external", // npm包
"internal", // 项目内部
"parent", // 父目录
"sibling", // 同级
"index" // 目录索引
],
"pathGroups": [
{
"pattern": "@/**", // 给别名路径特殊待遇
"group": "internal",
"position": "after"
}
],
"newlines-between": "always", // 分组间空行
"alphabetize": { // 字母表排序
"order": "asc",
"caseInsensitive": true
}
}
]
}
}
3. 开发流闭环(提体验)
通过配置 VSCode 的 .vscode/settings.json
文件,实现保存时自动应用 ESLint 修复:
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"]
}
Vue生态适配指南
对于 Vue 的 <script setup>
语法,可以通过微调 ESLint 的分组策略来适配:
"pathGroups": [
{
"pattern": "vue*", // 捕获vue全家桶
"group": "external",
"position": "before"
}
]
优化后的代码示例:
<script setup>
import { ref } from 'vue';
import { useStore } from 'vuex';
import { formatCurrency } from '@/libs/utils';
import ProductCard from './ProductCard.vue';
</script>
本文链接:
/archives/epx5V880
版权声明:
本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自
xxzz!
喜欢就支持一下吧