我一直在研究React Typescript存储库,并且遇到了一个烦人的问题,即开玩笑地说,它无法解析相对于根目录的导入。
Cannot find module '~lib/dates' from 'utils.ts'
这就是导入在组件/ utils中的样子
import { abc } from '~lib/dates'; // this fails to run
如果我将其更改为相对路径,则测试运行将按预期运行
import { abc } from '../../lib/dates'; // this runs as expected
相同的路径适用于其他目录,我有些困惑
import { xyz } from '~components/home/constants'; // jest resolves it
import { abc } from '~lib/dates'; // ERR
我尝试在jestConfig中包含moduleNameWrapper
,以查看它是否能正确解析导入,但无济于事。
package.json
"jest": {
...
"moduleNameWrapper": {
"^~(.*)$": "<rootDir>/src/$1"
}
}
我可以肯定地更新VS代码设置,以便自动导入相对于文件而不是使用根目录来解决,但这已经困扰了我一段时间。如果有人对如何最好地解决此问题有任何建议,那就太好了。
我正在使用具有以下目录结构的monorepo
repo
server
client
src
components
lib
utils
package.json
答案 0 :(得分:2)
您的实现看起来不错。但是看来选项moduleNameWrapper
是错误的选项,应该是moduleNameMapper
。
我也有一个与您相同的示例,该示例也使用babel作为转换器,在我添加moduleNameMapper
时效果很好。这是我的示例:
最好的配置:
https://github.com/tmhao2005/lerna-demo/blob/master/packages/helper/jest.config.js
这是要测试的文件:
https://github.com/tmhao2005/lerna-demo/blob/master/packages/helper/src/index.ts https://github.com/tmhao2005/lerna-demo/blob/master/packages/helper/src/index.test.ts
答案 1 :(得分:0)
忘记~
字符;
首先define root directory至开玩笑(即src/
);
然后从该根目录导入您的东西; (例如import { abc } from 'lib/dates'
)
通过这种方式,您始终可以从默认根目录导入内容,而无需进行以下任何配置:import { abc } from 'src/lib/dates'
如果正在使用create-react-app jest absolute import
,请进一步阅读