Module not found: Error: Can't resolve 'zlib'

Viewed 20497

I am trying to migrate a CRA react application to NX, following steps on the official site

When I hit nx serve

I am facing the following error:

ERROR in C:/dev/nx-dev/scandy/node_modules/@react-pdf/png-js/dist/png-js.browser.es.js Module not found: Error: Can't resolve 'zlib' in 'C:\dev\nx-dev\scandy\node_modules@react-pdf\png-js\dist'

ERROR in C:/dev/nx-dev/scandy/node_modules/@react-pdf/pdfkit/dist/pdfkit.browser.es.js Module not found: Error: Can't resolve 'zlib' in 'C:\dev\nx-dev\scandy\node_modules@react-pdf\pdfkit\dist'

Knowing that: before I start migration my project worked fine.

npm version: 6.14.11

node version: 14.16.0

I've tried to hit npm install zlib yet I get

Cannot find module './zlib_bindings'

2 Answers

For some reason, VSCode inserted import e from 'express' at the top of my file in react

import { response } from 'express';

I delete the above import line and then the problem is resolved, all the errors are gone after the above change.

It's about Webpack 5 and its default config you use for React app. I followed an advice from here: https://github.com/nrwl/nx/issues/4817#issuecomment-824316899 and React NX docs for how to use custom webpack config.

Create a custom webpack config, say, in /apps/myapp/webpack.config.js and reference it in workspace.json instead of "webpackConfig": "@nrwl/react/plugins/webpack". It should be "webpackConfig": "apps/myapp/webpack.config.js".

Content for webpack.config.js:

const nrwlConfig = require("@nrwl/react/plugins/webpack.js");

module.exports = (config, context) => {
  // first call it so that @nrwl/react plugin adds its configs
  nrwlConfig(config);

  return {
    ...config,
    node: undefined
  };
};

So, this config change makes webpack correctly understand what polyfills are needed.

Alternatively, you can do the following:

const nrwlConfig = require("@nrwl/react/plugins/webpack.js");

module.exports = (config, context) => {
  // first call it so that @nrwl/react plugin adds its configs
  nrwlConfig(config);

  return {
    ...config,
    resolve: {
      ...config.resolve,
      alias: {
        ...config.resolve.alias,
        stream: require.resolve('stream-browserify'),
        zlib: require.resolve('browserify-zlib'),  
      }
    }
  };
};
Related