解决import导入顺序杂乱无章的问题

​​

点击上方 前端Q,关注公众号

回复加群,加入前端Q技术交流群

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

解决方案 eslint-plugin-import

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

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

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 这个插件。使用方式如下:

安装插件:

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

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

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

自定义排序:

'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 `],
    ],
  },
],

这样就会按照我们系统中的功能模块排序了!

作者:热心市民王某
链接:https://juejin.cn/post/7281474941257220152
来源:稀土掘金

d599b4862bf51f30ddec0beaaf2d8c17.png

往期推荐

对不起 localStorage,现在我爱上 localForage了!

1ca2840534ea276d76f23fbea1825424.png

还原现场——前端录制用户行为技术方案

c4c529ef5a5997a0443ad747196bb56e.png

前端流程图插件对比选型,这一篇就够了

ab6e2666669e22361a8c046dc983d43f.png


最后

  • 欢迎加我微信,拉你进技术群,长期交流学习...

  • 欢迎关注「前端Q」,认真学前端,做个专业的技术人...

​​

9b446f8386b6d37c4c87337953e54102.jpeg

28628b91c225074553b9e67f179bedc5.png

点个在看支持我吧

ffda729001f7a63776ce665db4765748.gif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值