1. 程式人生 > 實用技巧 >使用crate-react-app建立的專案配置alias

使用crate-react-app建立的專案配置alias

使用crate-react-app建立的專案配置alias,這樣之後在專案中直接可以使用別名來訪問某個檔案目錄,從而快速引用某個檔案,如使用這個命令建立的專案中,我們這 src/ 目錄下建立一個 components/ 資料夾,如果想在專案中快速引用components/Tab/index.tsx 檔案的話,我們可這樣寫:import Tab from '@Component/Tab/index ,那麼我們是怎麼實現的呢?

首先我們在使用crate-react-app 建立專案後,進入到專案中執行 npm run eject 命令,將 react-script 外掛中封裝的 webpack、sass等配置檔案解壓到專案中(注意此命令不可逆,也就是說,一旦解壓後就不能更新 react-script 外掛版本來更新本地的配置檔案

)。

我們在 config/path.js 檔案中的 module.exports 內新增appComponents: resolveApp('src/components') ,如:

module.exports = {
  ...
  appComponents: resolveApp('src/components'),
  ...
};

接下來,我們開啟 config/webpack.config.js 檔案,在alias 物件中新增"@components": paths.appComponents,如:

alias: {
  ...
  "@components": paths.appComponents,
  ...
}

然後,我們開啟 tsconfig.json 檔案,在compilerOptions 物件中新增 ,如:

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

經過這三部設定後,你就可以在你的檔案中通過 @components 別名訪問到 src/components 檔案夾了,如:

我們在 src/ 資料夾下面新增 pages/ 資料夾,然後再新增一個 home/ 資料夾,在 home 資料夾下面新增 index.tsx 檔案。那麼我們在 src/pages/home/index.tsx 檔案裡面可以使用 import Tab from '@components/Tabindex' 來引入 src/components/Tab/index.tsx 檔案了.