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

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去寻找。

相关文章:

  • 2021-11-22
  • 2022-12-23
  • 2022-12-23
  • 2021-11-27
  • 2021-09-21
  • 2021-09-14
猜你喜欢
  • 2021-11-27
  • 2022-01-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-09
  • 2022-02-03
相关资源
相似解决方案