alias别名配置

在项目package.json中,可配置别名, 减少引用的麻烦。

假设我们有一个叫xxx的项目,用nanachi init xxx 创建后,大概是这个样子

alias

我们打开package.json在里面添加nanachi对象,nanachi下面再添加alias对象假设我们在assets目录下有一个global.scss,我们不想在pages在很深层次的目录中每次都要../../../assets/global.scss 地引用它。可以定义一个@assets别名,指向assets目录。由于当前执行命令在xxx目录下,assets又在source里,于是其路径为 source/assets

  1. {
  2. "license": "MIT",
  3. "version": "1.0.0",
  4. "name": "qunar",
  5. "nanachi": {
  6. "alias": {
  7. "@assets":"source/assets"
  8. }
  9. },
  10. "dependencies": {
  11. "regenerator-runtime": "^0.12.1"
  12. }
  13. }

使用方式,我们在某一个页面(/pages/xxx/yyy/index.js)添加一个index.scss, 其位置为pages/xxx/yyy/index.scss

  1. //index.js
  2. import React from '@react';
  3. import './index.scss';
  4. class P extends React.Component {
  5. //略
  6. }
  7. export default P
  8. //-------------- 略
  9. //index.scss
  10. @import '@assets/global.scss'
  11. .aaa {//其他样式
  12. color:red;
  13. }

在默认情况下, 每个项目的package.json/ nanachi / alias对象会添加两个别名@components与@react。因此添加别名时不要与它们冲突。

在业务开发中,我们把一些没有视图的业务逻辑放到common目录下,建议不同部门都有自己的XXXCommon.

  1. src
  2. |--components
  3. | |--HotelDialog
  4. | | └──index.js //必须以index.js命名,里面的类名 必须 与文件夹名一样, 如HotelDialog
  5. | |--HotelXXX
  6. | |--FlightYYY
  7. | └── ...
  8. |--pages
  9. | |--hotel
  10. | |--flight
  11. | |--holiday
  12. | |--strategy
  13. | └── ...
  14. |--common
  15. | |--hotelCommon
  16. | | └── ...
  17. | |--flightCommon
  18. | |--holidayCommon
  19. | |--strategyCommon
  20. | └── ...
  21. |--app.js

那么各部门可以这样定义自己的别名

  1. {
  2. "license": "MIT",
  3. "version": "1.0.0",
  4. "name": "qunar",
  5. "nanachi": {
  6. "alias": {
  7. "@assets":"source/assets",
  8. "@hotel" :"source/common/hotelCommon",
  9. "@train" :"source/common/trainCommon",
  10. "@flight" :"source/common/flightCommon"
  11. }
  12. },
  13. "dependencies": {
  14. "regenerator-runtime": "^0.12.1"
  15. }
  16. }

使用方式:

  1. import React from '@react'
  2. import trainPay from '@train/pay';
  3. //....其他代码