问题
I have following app structure:
Application AApplication BCommon package
Now Application A and B have in package.json the common package added:
{
dependencies: {
"commonPackage": "file:../../../commonPackage"
}
}
both apps use React, as well as the common package, all had React added with npm, and it worked, before we started to use react hooks.
Because when we started, we got an Invalid Hook Call Warning due to having "more than one copy of React", so to avoid that, in the common package, the react dependency was moved to peerDependencies so that the react instance from the app is used and not from the package.
It works great in the browser when we run both apps A and B, but when I run my mocha tests in the console, I get:
ERROR in ../commonPackage/~/@uifabric/utilities/lib/customizations/Customizer.js
Module not found: Error: Can't resolve 'react' in 'D:\myProject\commonPackage\node_modules\@uifabric\utilities\lib\customizations'
this is from the office-ui-fabric-react package we use, but it seems like a more general issue with dependency resolution.
Project is in TypeScript, we use webpack for the compilation of the app for the browser, and tsc to compile for the unit tests.
I found some answers, suggesting to npm link react in the common package to the react package in the application node_modules, but it seems wrong, since the common package is used by two applications, it would solve the issue only for one.
回答1:
In the case above we finally came to a solution which was
- adding back react as devDependency to
Common package - using
esmpackage to help our test runs understand es6 module export/import that came withfabricpackage. Just usingmocha --require esm ... ejecting and adding alias to
webpack.config.jsinApplicationalias: { 'react': path.resolve('./node_modules/react') }
Application A, B and hooks work now.
来源:https://stackoverflow.com/questions/57786415/cannot-find-module-when-running-unit-tests-on-node-js-with-react-as-peer-depen