Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Cannot find module" when running unit tests on node.js with react as peer dependency in common package

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.

like image 396
alek kowalczyk Avatar asked Jan 27 '26 01:01

alek kowalczyk


1 Answers

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.

like image 87
matprzybyla Avatar answered Jan 29 '26 14:01

matprzybyla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!