前端工程使用绝对路径代替相对路径

当项目的目录结构比较复杂时,如果使用相对路径,不仅不易读,而且容易写错。比如:

import MyUtilFn from '../../../../utils/MyUtilFn';

那么借助一个插件我们就可以实现绝对路径到相对路径的转换。

比如:

import MyUtilFn from '/utils/MyUtilFn';
babel-plugin-module-resolver
安装方法:
 npm install --save-dev babel-plugin-module-resolver或
 yarn add --dev babel-plugin-module-resolver

安装好后在babel的配置文件中加入:
{
  "plugins": [
    ["module-resolver", {
      "root": ["./src"],
      "alias": {
        "@common": "./src/common",
        "@constants": "./src/constants"
      }
    }]
  ]
}
以上配置表示把./src(.表示babel配置文件所在路径)作为根路径,也就是我们在import或require时只要写/xxx就会到./src/xxx去寻找。
下面的alias可有可无,意思是起一些别名,比如我们写'@common/xxx'就会到./src/common/xxx去寻找。

posted @ 2020-06-26 14:36  flamestudio  阅读(1151)  评论(0编辑  收藏  举报