1

Have references to navigator in multiple logics within our React project.

For example:

in MyComponent.jsx

export const isMobileDevice = /android|iPad|iPhone|iPod/i.test(navigator.userAgent);

These all works fine.

But when we perform a build using webpack, end up with following error.

log: ReferenceError: navigator is not defined
at Module../src/components/MyComponent.jsx (project-name@3.22.0:25348:21)
at __webpack_require__ (project-name@3.22.0:25348:30)

Seen few similar queries in past such as follows:

Window is not defined after a build with Webpack

Webpack 4 for SSR, How to solve this ReferenceError: window is not defined?

They all come down to adding the following in the wepack config as follows:

globalObject: 'this'

webpack.config.js

module.exports = {
  performance: {
    maxAssetSize: 1500, 
    maxEntrypointSize: 1500,
  },
  output: {
    globalObject: 'this', // this is what i added. There is nothing else in my webpack config file.
  },
};

After I deleted all generated files like .webpack-stats.client.json and .webpack-stats.server.json files. And run npm run build, the error still remains.

What am I missing?

package.json (related dependencies for webpack)

{
  "name": "project-name",
  "our-company-key": {
    "bundler": {
      "webpackConfigPath": "webpack.config.js"
    },
  },
  "scripts": {
    // other scripts
    "build": "company-build-using-webpack"
  },
  "devDependencies": {
    "clean-webpack-plugin": "^0.1.19",
    "compression-webpack-plugin": "^1.1.11",
    "uglifyjs-webpack-plugin": "^1.3.0",
    "webpack": "^4.39.3",
    "webpack-bundle-analyzer": "^4.0.0",
    "webpack-command": "^0.5.1",
    "webpack-node-externals": "^1.7.2",
    "webpack-serve": "^2.0.2"
  },
}
karvai
  • 2,417
  • 16
  • 31

0 Answers0