Fix Jest error: Cannot find module 'X' from 'Y'

发布于 2023-12-15 02:08:23 字数 1879 浏览 55 评论 0

在 monorepo 仓库(lerna + yarn + typescript)中运行 jest,结果报错 Cannot find module 'X' from 'Y',没想到是因为模块 X 中的 package.json 中没有 main 字段(jest 对 es6 支持不好

建议先检查跟 moduleNameMapper 有没有关系 kulshekhar/ts-jest#269,如果不相关,请检查被依赖的 module X 中的 package.json 中没有 main 字段

解决方法:

1、可通过 moduleNameMapper 映射,这样即使没有 main 字段,也可以正确解析:

moduleNameMapper: {
    '^@your_scope/module_a': '<rootDir>/../module_a/src/index.ts',
    '^@your_scope/module_b': '<rootDir>/../module_b/src/b.ts'
},

2、配置 ts,同时输出 es5、es6

tsc -p . --target es5 --outDir dist/es5 && tsc -p . --target es6 --outDir dist/es6

在 module X 的 package.json 新增 main 字段

"main": "dist/es5/x.js",
"module": "dist/es6/x.js",

3、使用 resovler 添加 main 字段,参考:

Support the "module" package.json field jestjs/jest#2702
https://github.com/makotoshimazu/jest-module-field-resolver/blob/master/src/index.js

如果依赖是 ES6 语法,jest 不会编译,会报错 SyntaxError:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

文章
评论
26 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文