React?Native項目設(shè)置路徑別名示例
正文
沒有設(shè)置路徑別名之前代碼是這樣的:
import { px2dp } from '../../utils/screenKits';
路徑相當冗長,看著就頭疼。增加了路徑別名之后,變成這樣
import { px2dp } from '~/utils/screenKits';
心里清爽多了!
具體操作見下文,實操性強!
安裝插件
這里我選用 babel-plugin-root-import插件,主要是方便,不需要再為了 eslint
不識別 '@' 而增加配置。
這個babel-plugin-module-resolver插件,也可以,但是需要處理 eslint 的配置
yarn add babel-plugin-root-import --dev
修改babel.config.js
module.exports = { presets: ['module:metro-react-native-babel-preset'], plugins: [ ['@babel/plugin-proposal-decorators', { legacy: true }], // mbox // ['react-native-reanimated/plugin'], [ 'babel-plugin-root-import', { paths: [ { rootPathSuffix: './src', rootPathPrefix: '~/', // 使用 ~/ 代替 ./src (~指向的就是src目錄) }, { rootPathSuffix: './src/utils', rootPathPrefix: '!/', }, ], }, ], ], };
修改import路徑測試
清除rn緩存并重新啟動項目
yarn clear-run
"scripts": { "android": "react-native run-android", "ios": "react-native run-ios", "start": "react-native start", "test": "jest", "lint": "npx eslint --ext .js,.jsx,.ts,.tsx ./src", "lint:fix": "npx eslint --fix .", "check": "lint-staged", "format": "prettier --write 'src/**/*.js'", "prettier": "npx prettier --write .", "prepare": "husky install", "clear": "yarn cache clean", "clear-run": "react-native start --reset-cache", "del": "rimraf node_modules yarn.lock" },
可以看到項目可以正常啟動、正常運行
修復函數(shù)跳轉(zhuǎn)到定義功能
配置vscode: https://code.visualstudio.com/docs/languages/jsconfig再項目根目錄增加 jsconfig.json
文件
{ "compilerOptions": { "baseUrl": ".", // 基礎(chǔ)目錄 "paths": { // 指定相對于 baseUrl 選項計算的路徑映射, 別名路徑也可以跳轉(zhuǎn) "~/*": [ "src/*" ] } } }
這個配置是針對編輯器的,不用重啟項目,配置即生效
以上就是React Native項目設(shè)置路徑別名示例的詳細內(nèi)容,更多關(guān)于React Native路徑別名的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
React Hook 父子組件相互調(diào)用函數(shù)方式
這篇文章主要介紹了React Hook 父子組件相互調(diào)用函數(shù)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09完美解決react-codemirror2?編輯器需點擊一下或者延時才顯示數(shù)據(jù)的問題
這篇文章主要介紹了react-codemirror2編輯器需點擊一下或者延時才顯示數(shù)據(jù)的問題,解決方法也很簡單,需要手動引入自動刷新的插件,配置一下參數(shù)就可以了,本文給大家介紹的非常詳細,需要的朋友可以參考下2023-08-08