3

I have following app structure:

  • Application A
  • Application B
  • Common 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.

alek kowalczyk
  • 4,896
  • 1
  • 26
  • 55
  • If your `mocha` tests are in `commonPackage` and you need React for test purposes in common, you could it as `devDependency`. – ford04 Sep 04 '19 at 13:19

1 Answers1

4

In the case above we finally came to a solution which was

  • adding back react as devDependency to Common package
  • using esm package to help our test runs understand es6 module export/import that came with fabric package. Just using mocha --require esm ...
  • ejecting and adding alias to webpack.config.js in Application

        alias: {
            'react': path.resolve('./node_modules/react')
        }
    

Application A, B and hooks work now.

  • Yea! This worked for me. I was only using fabric (so far) in my applications, not the common package, so I didn't need the `--require esm` part, but this last step, adding the `alias` to the `resolve` section of my `webpack.config.js` is what got me working again. – Stokesified Aug 27 '21 at 12:14
  • For me this one was the solution: https://stackoverflow.com/questions/64365016/jest-cannot-find-module-react-and-other-node-modules – Ariel Batista Sep 20 '22 at 13:22