# React + craco + alias + Vscode 配置設定 ###### tags: `React` `craco` `alias` `configure` 使用 CRA(created-react-app) 建立項目時,如果想要完全的控制依賴項目(Webpack, Babel 等),可以執行 script [`npm run eject`](https://segmentfault.com/a/1190000038221692),但這是個不可逆操作,也將無法跟隨官方升級 `react-script` 版本。(目前也沒有執行過這個指令) 既然這樣就使用 craco 來覆蓋配置,以及設定 alias path 自定路由並且讓 Vscode 讀懂,就能顯示配置路由下的檔案以及直接跳轉至檔案。 ## 配置步驟: ### 1. 安裝 ``` yarn add @craco/craco ``` ### 2. 修改 `package.json` 裡的 `script` 指令 刪除 `react-script` 由 craco 來啟動 ```javascript "scripts": { "start": "craco start", "build": "craco build", "test": "craco test", "eject": "craco eject" }, ``` ### 3. 建立 `craco.config.js` 並且設定 alias 別名路徑 ```javascript const path = require('path'); module.exports = { webpack: { alias: { '@': path.resolve(__dirname, 'src/'), '@COM': '@/components', '@HOOK': '@/hook', }, } } ``` ### 4. 建立 `jsconfig.json` (Vscode 的設定 ```json { "compilerOptions": { "baseUrl": "./", "paths": { "@/*": ["src/*"], "@COM/*": ["src/components/*"], "@hook/*": ["src/hook/*"], } }, "exclude": ["node_modules", "dist"], "include": ["src/**/*"] } ``` #### Reference: - [How to intellisense alias module path in VSCode](https://stackoverflow.com/questions/58249053/how-to-intellisense-alias-module-path-in-vscode) - [Vscode中alias跳转(别名路径跳转-解决@跳转)_宅男呀-程序员ITS203](https://www.its203.com/article/Sheng_zhenzhen/109377431) ### 5. 建議重啟 vscode 並執行 ``` yarn start ``` 到專案中引入元件 輸入 `@COM/` 時就可以看到 vscode 讀取到資聊夾內的所有元件了 ![](https://i.imgur.com/85T6MG5.png) ![](https://i.imgur.com/2qJxo62.png) command 鍵按著點選路徑,就能夠直接跳轉到該元件了 玩玩看鱉~ ![](https://i.imgur.com/Lvswtw3.png)