【问题标题】:How to refer components without typing the complete relative path?如何在不输入完整相对路径的情况下引用组件?
【发布时间】:2019-04-13 08:08:39
【问题描述】:
src
components
HomePage
Calendar.js
containers
HomePage
index.js
我只是在 React(Presentation + Container) 中使用推荐的文件夹结构。当我在处理react-boilerplate 文件夹结构时,我可以在 components 文件夹中引用组件而不列出相对路径 import Calendar from 'components/HomePage/Calendar';。如何在我的项目中做到这一点,而无需输入完整的相对路径 import Calendar from '../../components/HomePage/Calendar';
?
【问题讨论】:
标签:
javascript
reactjs
react-boilerplate
【解决方案1】:
以下 .babelrc 文件使我能够使用 myproject/components/HomePage/Calendar 而不是 ../../components/HomePage/Calendar 来引用组件:
{
"env": {
"development": {
"plugins": [
["module-resolver", {
"alias": {
"myproject": "./src",
}
}]
]
},
"production": {
"plugins": ["transform-remove-console"]
}
}
}
【解决方案2】:
分别根据您的项目、javascript 或 typescript 创建 jsconfig.json 或 tsconfig.json。
在 json 文件中。
- baseUrl 是所有文件夹的文件夹,如组件、容器
和定位的上下文。
- 在 json 路径中,键是 baseUrl 中的文件夹
文件夹,但您不能指定父文件夹中的每个文件夹。
我的项目 sn-p。
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"screens/*": ["src/screens/*"],
"components/*": ["src/components/*"],
"utils/*": ["src/utils/*"]
}
}
}
像这样。
{
"compilerOptions": {
"baseUrl": "your top most parent folder",
}
}