如何使用绝对路径解析导入?

How do I resolve import with absolute path?

我需要在 brunch-config.js 中设置什么才能解析项目根文件夹的绝对路径?即

import { helper } from '/imports/utilities/helper'

原因是我有一个遗留的 React 应用程序,它使用相对路径导入本地文件。当我尝试使用 brunch 时,我需要找出一种设置 brunch 的方法,以便它在无需更改代码的情况下理解路径。

我尝试使用 npm 别名但不确定它是如何工作的

npm: {
  aliases: {
    '/imports': 'imports/**'
  }
}

找到 babel-plugin-module-resolver 包的解决方案。

因为我所有的代码都在 /imports 目录下,在 brunch-config.js 中我根据他们的 documentation:

设置了一个别名
plugins: {
  babel: {
    plugins: [
      ...,
      ["module-resolver", {
        "root": ["./imports"],
        "alias": {
          "/imports": ([, path]) => `./imports${path}`,
        }
      }]
    ],
    presets: [
      ...
    ],
  }
},

那样的话,如果我 import Screen from '/imports/components/screens' 它会解析 ./imports/components/screens

下的文件

您也可以在 .babelrc 中设置别名,但您可能想改用正则表达式。