Search code examples
javascriptreactjswebpackwebpack-dev-serverumd

Error: Cannot read property 'PureComponent' of undefined


I am creating a external npm package .My package bundle is successfully created but when I am putting the bundle.js on console it give is this error

Error: Cannot read property 'PureComponent' of undefined

here is my webpack config

const config = {
    // TODO: Add common Configuration
    mode: "production",
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: "babel-loader"
            }
        ]
    },
};

const fooConfig = Object.assign({}, config, {
    name: "header_react_next",
    entry: "./src/index.js",
    output: {
        path: path.resolve("build"),
        libraryTarget: "umd",
        library: "header",
        filename: `index.js`,
    },
    externals: {
        'react': 'react',
        'react-dom': 'react-dom',
    },
    plugins: [

    ]
});

module.exports = [
    fooConfig
];

it create the bundle but when I am putting that bundle file on console it give me above error

here is my code with bundle.

enter image description here

these are my devdependancs

 "devDependencies": {
    "@babel/core": "^7.13.1",
    "@babel/preset-env": "^7.13.5",
    "@babel/preset-react": "^7.12.13",
    "babel-loader": "^8.2.2",
    "react": "^17.0.1",
    "webpack": "^5.24.1",
    "webpack-cli": "^4.5.0"
  },
  "dependencies": {
    "axios": "^0.21.1",
    "react-input": "^3.2.3"
  }

Solution

  • PureComponent is imported from react package.

    But in your Webpack config you've declared it as external.

        externals: {
            'react': 'react',
            'react-dom': 'react-dom',
        },
    

    This declaration means that Webpack does not need to bundle 'react' and 'react-dom' packages (from your node_modules) into bundle.js and expects those libraries to be pre-loaded in your HTML.

    Please update Webpack config to include React and ReactDOM (those variable names are used by default in react and react-dom)

        externals: {
            'react': 'React',
            'react-dom': 'ReactDOM',
        },
    

    and include react and react-dom in your HTML (before bundle.js)

      <!-- Load React. -->
      <script src="https://unpkg.com/react@17/umd/react.production.min.js" crossorigin></script>
      <script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js" crossorigin></script>
    
      <!-- Load your Webpack bundle -->
      <script src="bundle.js"></script>