沒有設置路徑別名之前代碼是這樣的:
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ù)跳轉到定義功能
配置vscode: https://code.visualstudio.com/docs/languages/jsconfig
再項目根目錄增加 jsconfig.json
文件
{
"compilerOptions": {
"baseUrl": ".", // 基礎目錄
"paths": { // 指定相對于 baseUrl 選項計算的路徑映射, 別名路徑也可以跳轉
"~/*": [
"src/*"
]
}
}
}
這個配置是針對編輯器的拨黔,不用重啟項目,配置即生效
我是 甜點cc?
公眾號:【看見另一種可能】