import导入顺序杂乱的问题

我们经常会遇到项目中的import语句顺序混乱的问题。这不仅会影响代码的可读性,还可能使我们代码在提交的时候产生不必要的冲突。

解决方案

eslint-plugin-import

开始我调研了一下eslint-plugin-import插件。这款插件的排序逻辑是这样:

  1. builtin : 这代表Node.js内置的模块,例如fspath等。

    import fs from 'fs';

  2. external: 这代表外部库或框架,通常是你通过npm或yarn安装的模块。

    import axios from 'axios';

  3. internal: 这代表项目内部的模块,但它们通常在项目的不同目录或子目录中。这些模块不是直接的父级或同级模块。

    import { someFunction } from '@utils/my-helper';

  4. parent: 这代表从父目录导入的模块。

    import something from '../something';

  5. sibling: 这代表与当前文件在同一目录下的其他文件。

    import { siblingFunction } from './sibling-module';

  6. index : 这代表从目录的index文件导入的模块。

    import { indexFunction } from './';

  7. object: 这代表导入的对象属性,例如:

    import('some-module').then(({ someExport }) => ...);

  8. type: 这代表从模块导入的类型或接口(这在TypeScript中特别有用)。

    import type { MyType } from './types';

大致分为这些模块。我们可以在eslint的规则中根据这些模块进行排序。但是这并不是我想要的排序模式,我更希望根据功能进行排序。组件放在一起,hooks放在一起,工具函数放在一起,等等。

eslint-plugin-simple-import-sort

于是我找到了eslint-plugin-simple-import-sort这个插件。使用方式如下:

  1. 安装插件:

    npm install --save-dev eslint-plugin-simple-import-sort

  2. 配置 ESLint : 在 .eslintrc.js 或你的 ESLint 配置文件中,添加以下配置:

    module.exports = {
    // ... 其他配置
    plugins: ['simple-import-sort'],
    rules: {
    'simple-import-sort/imports': 'error',
    'simple-import-sort/exports': 'error',
    },
    };

  3. 自定义排序:

    复制代码
     'simple-import-sort/imports': [
      'error',
      {
        groups: [
          [`^vue$`, `^vue-router$`, `^ant-design-vue$`, `^echarts$`], // 你可以根据需要添加更多的内置模块
            [`.*\\.vue$`], // .vue 文件
            [`.*/assets/.*`, `^@/assets$`],
            [`.*/config/.*`, `^@/config$`],
            [`.*/hooks/.*`, `^@/hooks$`],
            [`.*/plugins/.*`, `^@/plugins$`],
            [`.*/router/.*`, `^@/router$`],
            [`^@/services$`, `^@/services/.*`],
            [`.*/store/.*`, `^@/store$`],
            [`.*/utils/.*`, `^@/utils$`],
            [`^`],
            [`^type `],
        ],
      },
    ],
相关推荐
打瞌睡的朱尤1 小时前
Vue day10 完整购物网页(登录页,首页,搜索)
前端·javascript·vue.js
扶苏10022 小时前
深入理解 Vue 3 的 watchEffect
前端·javascript·vue.js
unable code3 小时前
内存取证-卡比卡比卡比
网络安全·ctf·misc·1024程序员节·内存取证
打瞌睡的朱尤5 小时前
Vue day9 购物车,项目,vant组件库,vw,路由
前端·javascript·vue.js
何中应9 小时前
使用Jenkins部署前端项目(Vue)
前端·vue.js·jenkins
EstherNi10 小时前
仿照elementui写图片放大的案例,但多加了下载按钮,vue3
javascript·vue.js·elementui
JosieBook11 小时前
【Vue】15 Vue技术——Vue计算属性简写:提升代码简洁性的高效实践
前端·javascript·vue.js
rfidunion11 小时前
springboot+VUE+部署(11。Nginx)
linux·vue.js·nginx
学传打活11 小时前
【边打字.边学昆仑正义文化】_3_宇宙人类演化史(2)
微信公众平台·1024程序员节·汉字·昆伦正义文化
拾荒李14 小时前
在 Vue 项目里“无痛”使用 React 组件:以 Veaury + Vite 为例
前端·vue.js·react.js