我们在开发一个页面的时候,文件头部总是会有一堆 import 代码,特别是使用 React 技术栈的同学感同身受,随着项目代码的增多,如果不对头部的代码进行分层,会导致代码看起来很冗余,我们需要它按照一定的规则进行排序。
问题本质
当头部 import 代码过多时,它往往是这样的:
TypeScript 代码:import { useAntdTable, useBoolean, useRequest, useSetState } from 'ahooks' import type { ColumnsType, ColumnType } from 'antd/es/table'; import ImportFileModal from './components/ImportFileModal' import ImportFundReceiptListTable from './components/ImportFundReceiptListTable' import { get, reduce, toNumber } from 'lodash' import moment, { Moment } from 'moment' import React, { FC, useState } from 'react' import { Link } from 'react-router-dom'; import PageHeaderWrapper from '@/components/PageHeaderWrapper'; import { transPostToGet } from '@/utils/utils'; import ImportErrorModal from './components/ImportErrorModal' import ImportNumberModal from './components/ImportNumberModal' import TrendTotal from './components/TrendTotal' import { Button, Card, Col, DatePicker, Form, Row, Space, Table } from 'antd' import { FundReceiptTable, Json2DBParams, TableParams } from './utils/interface' import { generatePageJson, getReceiptList, saveJsonDB } from './utils/service'
如果不进行处理,可读性极差,对于有强迫症的我实在忍不了。
配置 Eslint
Eslint官网 本身提供了一条名叫 sort-imports 的规则,首先我们需要安装一个插件 eslint-plugin-simple-import-sort:
POWERSHELL 代码:pnpm add -D eslint-plugin-simple-import-sort
配置 .eslintrc.cjs 文件,加入配置:
JSON 代码:{ "plugins": ["simple-import-sort"], "rules": { "simple-import-sort/imports": "error", } }
这样我们就配置好了,以后当我们开发页面的时候,Eslint 会自动帮我们把头部的 import 代码进行排序。
排序后是这样的:
TypeScript 代码:import { useAntdTable, useBoolean, useRequest, useSetState } from 'ahooks' import { Button, Card, Col, DatePicker, Form, Row, Space, Table } from 'antd' import type { ColumnsType, ColumnType } from 'antd/es/table'; import { get, reduce, toNumber } from 'lodash' import moment, { Moment } from 'moment' import React, { FC, useState } from 'react' import { Link } from 'react-router-dom'; import PageHeaderWrapper from '@/components/PageHeaderWrapper'; import { transPostToGet } from '@/utils/utils'; import ImportErrorModal from './components/ImportErrorModal' import ImportFileModal from './components/ImportFileModal' import ImportFundReceiptListTable from './components/ImportFundReceiptListTable' import ImportNumberModal from './components/ImportNumberModal' import TrendTotal from './components/TrendTotal' import { FundReceiptTable, Json2DBParams, TableParams } from './utils/interface' import { generatePageJson, getReceiptList, saveJsonDB } from './utils/service'
怎么样,是不是可读性变好很多!