Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
hughfenghen opened this issue Dec 15, 2020 · 1 comment
Open

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

hughfenghen opened this issue Dec 15, 2020 · 1 comment

Comments

@hughfenghen
Copy link
Owner

hughfenghen commented Dec 15, 2020

在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'
},
  1. 配置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",
  1. 使用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:
@hughfenghen hughfenghen changed the title Jest cannot find module xxx Fix Jest error: Cannot find module 'X' from 'Y' Dec 15, 2020
@Creabine
Copy link

666,感谢,得救了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants