Say Goodbye to '../' '../../' '../../../'

開發 JavaScript 時,你有沒有遇到過這樣的狀況。
頁面複用大量共通組件,這些共通組件大致都在同一個文件夾下。可是因爲組件分割和文件夾層級較深的緣故,你嚐嚐會寫出👇這樣的代碼。前端

// some.js
import VodMediaPlayer from '../../../components/VodVideo/VodMediaPlayer'
import VideoInfo from '../../../components/VodVideo/VideoInfo'
import RecommendList from '../../../components/RecommendList/RecommendList'
import Comment from '../../../components/Comment/Comment'
import { get, mediaPath } from '../../../util/fetch'
import { API_VIDEO, API_CHANNEL } from '../../../util/constants'

你知道本身在鍵盤上敲擊 ../ ../../ ../../../ 時浪費了多少時間嗎?react

時間就是金錢。 ~名言

爲了解決這種問題,主流的前端工具都給出瞭解決方案。
本文介紹如何使用 babel plugin 的解決方案。git

正文

首先咱們選擇 babel-plugin-module-resolvergithub

1. 安裝

$ npm install --save-dev babel-plugin-module-resolver

2. 配置 .babelrc

{
  "presets": ["env", "react"],
  "plugins": [
    ["module-resolver", {
      "root": ["./"],
      "alias": {
        "components": "./src/components",
        "util": "./src/util"
      }
    }]
}

這時你的代碼能夠修改成👇npm

// some.js
import VodMediaPlayer from 'components/VodVideo/VodMediaPlayer'
import VideoInfo from 'components/VodVideo/VideoInfo'
import RecommendList from 'components/RecommendList/RecommendList'
import Comment from 'components/Comment/Comment'
import { get, mediaPath } from 'util/fetch'
import { API_VIDEO, API_CHANNEL } from 'util/constants'

⚠️注意: 若是你使用了 eslint,這時 eslint 會報錯,由於它不能處理新的寫法。json

3. 添加對應的 eslint plugin

咱們選擇 eslint-import-resolver-babel-modulebabel

$ npm install --save-dev eslint-plugin-import eslint-import-resolver-babel-module

配置 .eslintrcide

"settings": {
  "import/resolver": {
    "babel-module": {}
  }
}

⚠️注意: 這時 eslint 不會報錯了, 可是你會發現你點擊 import 後面的組件名, VSCode 不會自動跳轉到組件定義。工具

4. 在項目根目錄下添加 jsconfig.json 解決

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "components/*": ["src/components/*"],
      "util/*": ["src/util/*"],
      "locales/*": ["src/locales/*"]
    }
  }
}

到此爲止,咱們終於能夠 Say Goodbye to '../' '../../' '../../../' 了。fetch

參考

https://github.com/parcel-bun...
https://github.com/tleunen/ba...
https://code.visualstudio.com...

相關文章
相關標籤/搜索