安装
项目根目录下运行指令
npm install babel-plugin-root-import --save-dev
or
yarn add babel-plugin-root-import --dev
完成后修改根目录下的配置文件 .babelrc
{
"plugins": [
[
"babel-plugin-root-import",
{
"rootPathSuffix": "./src",
"rootPathPrefix": "@/"
}
]
]
}
@ 是 src对应的别名
然后你就能在项目里这样引入文件了
import login from '@/pages/login';
如果有多个路径别名需要配置
"plugins": [
[
"babel-plugin-root-import",
{
"paths": [
{
"rootPathSuffix": "./src/components",
"rootPathPrefix": "~/"
},
{
"rootPathSuffix": "./src/utils",
"rootPathPrefix": "!/"
},
]
}
]
],
ps:已有项目需要先清理缓存 关闭监听程序
watchman watch-del-all
react-native start "--reset-cache"
VSCode 配置支持别名路径智能提示
VSCode安装组件 Path Intellisense
再到项目根目录下新建文件jsconfig.json
{
"compilerOptions": {
"target": "es6",
"baseUrl": ".",
"paths": {
"@/*": [
"src/*"
]
}
},
"exclude": [
"node_modules"
]
}