解決import導(dǎo)入順序雜亂無章的問題
點擊上方 前端Q ,關(guān)注公眾號
回復(fù) 加群 ,加入前端Q技術(shù)交流群
我們經(jīng)常會遇到項目中的 import 語句順序混亂的問題。這不僅會影響代碼的可讀性,還可能使我們代碼在提交的時候產(chǎn)生不必要的沖突。
解決方案 eslint-plugin-import
開始我調(diào)研了一下 eslint-plugin-import 插件。這款插件的排序邏輯是這樣:
-
builtin: 這代表Node.js內(nèi)置的模塊,例如fs、path等。
import fs from 'fs';
-
external: 這代表外部庫或框架,通常是你通過npm或yarn安裝的模塊。
import axios from 'axios';
-
internal: 這代表項目內(nèi)部的模塊,但它們通常在項目的不同目錄或子目錄中。這些模塊不是直接的父級或同級模塊。
import { someFunction } from '@utils/my-helper';
-
parent: 這代表從父目錄導(dǎo)入的模塊。
import something from '../something';
-
sibling: 這代表與當(dāng)前文件在同一目錄下的其他文件。
import { siblingFunction } from './sibling-module';
-
index: 這代表從目錄的index文件導(dǎo)入的模塊。
import { indexFunction } from './';
-
object: 這代表導(dǎo)入的對象屬性,例如:
import('some-module').then(({ someExport }) => ...);
-
type: 這代表從模塊導(dǎo)入的類型或接口(這在TypeScript中特別有用)。
import type { MyType } from './types';
大致分為這些模塊。我們可以在 eslint 的規(guī)則中根據(jù)這些模塊進行排序。但是這并不是我想要的排序模式,我更希望根據(jù)功能進行排序。組件放在一起,hooks 放在一起,工具函數(shù)放在一起,等等。
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$`], // 你可以根據(jù)需要添加更多的內(nèi)置模塊
[`.*\\.vue$`], // .vue 文件
[`.*/assets/.*`, `^@/assets$`],
[`.*/config/.*`, `^@/config$`],
[`.*/hooks/.*`, `^@/hooks$`],
[`.*/plugins/.*`, `^@/plugins$`],
[`.*/router/.*`, `^@/router$`],
[`^@/services$`, `^@/services/.*`],
[`.*/store/.*`, `^@/store$`],
[`.*/utils/.*`, `^@/utils$`],
[`^`],
[`^type `],
],
},
],
這樣就會按照我們系統(tǒng)中的功能模塊排序了!
作者:熱心市民王某
鏈接:https://juejin.cn/post/7281474941257220152
來源:稀土掘金
往期推薦
還原現(xiàn)場——前端錄制用戶行為技術(shù)方案
前端流程圖插件對比選型,這一篇就夠了
最后
-
歡迎加我微信,拉你進技術(shù)群,長期交流學(xué)習(xí)...
-
歡迎關(guān)注「前端Q」,認(rèn)真學(xué)前端,做個專業(yè)的技術(shù)人...
點個在看支持我吧
