Error: Cannot read property 'PureComponent' of undefined

Error: Cannot read property 'PureComponent' of undefined

我正在创建一个外部 npm 包。我的包包已成功创建,但是当我将 bundle.js 放在控制台上时,它给出了这个错误

错误:无法读取未定义的 属性'PureComponent'

这是我的 webpack 配置

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
];

它创建了包,但是当我将该包文件放在控制台上时,它给我上面的错误

here is my code with bundle.

这些是我的开发依赖

 "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"
  }

PureComponent 是从 react 包导入的。

但是在您的 Webpack 配置中,您已将其声明为外部。

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

此声明 means Webpack 不需要将 'react' 和 'react-dom' 包(来自您的 node_modules)捆绑到 bundle.js 中并期望这些库预加载到您的 HTML.

请更新 Webpack 配置以包含 ReactReactDOM(这些变量名默认用于 react 和 react-dom)

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

并在 HTML 中包含 react 和 react-dom(在 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>