• import导入顺序杂乱的问题


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

    解决方案

    eslint-plugin-import

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

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

    import fs from 'fs';
    
    1. external: 这代表外部库或框架,通常是你通过npm或yarn安装的模块。

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

    import { someFunction } from '@utils/my-helper';
    
    1. parent: 这代表从父目录导入的模块。

    import something from '../something';
    
    1. sibling: 这代表与当前文件在同一目录下的其他文件。

    import { siblingFunction } from './sibling-module';
    
    1. index: 这代表从目录的index文件导入的模块。

    import { indexFunction } from './';
    
    1. object: 这代表导入的对象属性,例如:

    import('some-module').then(({ someExport }) => ...);
    
    1. 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
    
    1. 配置 ESLint: 在 .eslintrc.js 或你的 ESLint 配置文件中,添加以下配置:

    1. module.exports = {
    2.      // ... 其他配置
    3.      plugins: ['simple-import-sort'],
    4.      rules: {
    5.        'simple-import-sort/imports''error',
    6.        'simple-import-sort/exports''error',
    7.      },
    8.    };
    1. 自定义排序:

    1.     'simple-import-sort/imports': [
    2.      'error',
    3.      {
    4.        groups: [
    5.          [`^vue$`, `^vue-router$`, `^ant-design-vue$`, `^echarts$`], // 你可以根据需要添加更多的内置模块
    6.            [`.*\\.vue$`], // .vue 文件
    7.            [`.*/assets/.*`, `^@/assets$`],
    8.            [`.*/config/.*`, `^@/config$`],
    9.            [`.*/hooks/.*`, `^@/hooks$`],
    10.            [`.*/plugins/.*`, `^@/plugins$`],
    11.            [`.*/router/.*`, `^@/router$`],
    12.            [`^@/services$`, `^@/services/.*`],
    13.            [`.*/store/.*`, `^@/store$`],
    14.            [`.*/utils/.*`, `^@/utils$`],
    15.            [`^`],
    16.            [`^type `],
    17.        ],
    18.      },
    19.    ],
  • 相关阅读:
    MacOS 文件句柄数不够 Error: EMFILE: too many open files
    【【萌新的SOC学习之基于BRAM的PS和PL数据交互实验】】
    java面向对象(三)
    RESTful 风格是指什么
    进度猫:时间管理工作原则
    el-date-picker 有效时间精确到时分秒 且给有效时间添加标记
    PTA--1087 All Roads Lead to Rome(最短路计数+输出路径)
    C++之类和对象(上)
    在不同操作系统上如何安装符号表提取工具(eu-strip)
    【网站项目】书籍销售系统小程序
  • 原文地址:https://blog.csdn.net/why_1639946449/article/details/134024324