react-native路徑別名
介紹
import導入模塊的時候,需要使用相對路徑,例如../../../../test, 如果相對路徑太長了,不能夠特別直觀得看出模塊的真實路徑。最主要的如果某一個模塊更換位置,有可能import路徑都需要修改。
那如果使用路徑別名,例如 @/atom/test, @代表src,會更直觀一些
配置
1. 安裝 babel-plugin-root-import
yarn add --dev babel-plugin-root-import
2. 配置babel
babel.config.js
module.exports = {
...
plugins: [
[
"babel-plugin-root-import",
{
rootPathSuffix: "./src",
rootPathPrefix: "@/"
}
]
]
}
3. 配置tsconfig
tsconfig.json
{
...
"compilerOptions": {
...
"baseUrl": ".",
"paths": {
"@/*": [
"src/*"
]
},
...
},
...
}