调整目录结构(alias,routes)
从这一小节,开始我们将会对上一章节的demo,进行页面的美化和功能的完善。
规划pages下的目录结构
现在我们的pages目录结构如下:
.
├── hero.css
├── hero.js
├── index.css
├── index.js
├── item.css
├── item.js
├── summoner.css
└── summoner.js
这样的目录结构,当我们的页面越来越多时,或者页面需要的功能文件(model,service,mock等)越来越多时,就会使我们的项目非常凌乱。 所以我们先对pages下的目录结构重新规划
- step1 将hero.js重命名为hero/index.js
- step2 将hero.css重命名为hero/index.css
- step3 添加文件夹
./src/pages/hero/services/
(空文件夹暂时用不着,添加.gitkeep) - step4 添加文件夹
./src/pages/hero/components/
(空文件夹暂时用不着,添加.gitkeep) - step5 将
./src/models/hero.js
移动到./src/pages/hero/models/hero.js
```bash ERROR Failed to compile with 1 errors 08:54:02
This relative module was not found:
- ../services/api in ./src/pages/hero/models/hero.js
这里我们添加了我们现有的几个目录的映射。这样子我们在项目中就可以直接使用别名来代替相对路径来。 如这时候会有一个报错,因为我们在model里面对文件的引用使用的是相对路径。
所以当移动到pages目录下时,就会出现如上引用路径错误的问题。
## 添加alias别名
这里我们使用webpack的别名来处理这个问题,
在umi中使用非常简单,只要在配置文件里面,添加alias配置
```javascript
const path = require('path');
export default {
plugins: [
...
],
alias: {
utils: path.resolve(__dirname, 'src/utils'),
services: path.resolve(__dirname, 'src/services'),
models: path.resolve(__dirname, 'src/models'),
},
};
不论是在项目中的哪个目录下面引用,都不会找不到文件。 最终我们规划好的pages下的文件结构如下import { queryHeroList, getHeroDetails } from 'services/api';
由于umi约定了,pages下的目录会被解析成路由,你可以通过访问一个错误的路由地址,来重定向到开发404页面,查看你现有的所有路由。 如,此时我们访问.
├── hero
│ ├── components
│ │ └── .gitkeep
│ ├── index.css
│ ├── index.js
│ ├── models
│ │ └── hero.js
│ └── services
│ └── .gitkeep
...
http://localhost:8000/hero1
但是有时候我们只是把某些文件放在pages目录下面,但并不希望用它来生成任何路由,如我们现在的models文件,即Your Routes
-/
--/hero
--/hero/models/hero
--/
--/item
--/summoner
/hero/models/hero
这个路由是我们不需要的。(可能你还会在pages下面放images之类的)配置routes的exclude
这时候,我们可以通过配置routes的exclude来过滤掉一些文件。
再次访问const path = require('path');
export default {
plugins: [
[
'umi-plugin-react',
{
...
routes: {
exclude: [
/model\.(j|t)sx?$/,
/service\.(j|t)sx?$/,
/models\//,
/components\//,
/services\//,
],
}
},
],
],
...
};
http://localhost:8000/hero1
Your Routes
-/
--/hero
--/
--/item
--/summoner
作业
参照上面的操作,完成item、summoner页面的目录结构修改。 最终我们的pages目录结构为
.
├── hero
│ ├── components
│ │ └── .gitkeep
│ ├── index.css
│ ├── index.js
│ ├── models
│ │ └── hero.js
│ └── services
│ └── .gitkeep
├── index.css
├── index.js
├── item
│ ├── components
│ │ └── .gitkeep
│ ├── index.css
│ ├── index.js
│ ├── models
│ │ └── item.js
│ └── services
│ └── .gitkeep
└── summoner
├── components
│ └── .gitkeep
├── index.css
├── index.js
├── models
│ └── summoner.js
└── services
└── .gitkeep
代码回顾:这节课的全部代码