You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

导入React组件获取空对象,组件无法渲染问题求助

React组件npm模块导入错误问题解决

问题描述

我在standalone.js中编写了基础React组件:

import React from "react"

function MyPromosComponent() {
  console.log('PHK - IN MY PROMOS COMPONENT');
  return <h1>TEST FROM MY PROMOS</h1>;
}

export default MyPromosComponent;

使用以下webpack配置构建:

module.exports = {
    output: {
          path: __dirname,
          filename: "dist/index.js",
          libraryTarget: "var",
          jsonpFunction: "webpack_jsonp_gbundles"
    },
    entry: {
        main: './src/standalone'
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: ["style-loader", "css-loader"],
            },
            {
                test: /\.scss$/i,
                use: ["style-loader", "css-loader", "sass-loader"],
            },
            {
                test: /\.(js|jsx)$/,
                use: "babel-loader",
            },
        ],
    },
}

package.json已配置main: "dist/index.js",但在其他项目中安装导入该组件时,出现错误:

Warning: React.createElement: type is invalid -- expected a string (for built-in components)
or a class/function (for composite components) but got: object.
You likely forgot to export your component from the file it's defined in,
or you might have mixed up default and named imports.
Check your code at App.js:19.
in App (at src/index.js:6)

导入组件的App.js代码:

import React from 'react';

import MyPromosComponent from 'my-promos-page-client';

function App() {
  console.log('PHK ??? ', MyPromosComponent);

  return (
    <div className="App">
      <h1>TEST</h1>
      <MyPromosComponent /> <!-- line 19 in App.js -->
    </div>
  );
}

export default App;

我已使用默认导出,请问问题出在哪里?是否是webpack配置存在问题?

问题原因与解决方案

问题出在webpack的output配置上:当前设置的libraryTarget: "var"是将打包后的代码暴露为全局变量,而非符合CommonJS/npm模块规范的导出格式。当其他项目通过import导入时,拿到的是webpack打包生成的模块容器对象,而非你默认导出的组件函数,因此React无法识别为有效的组件类型。

解决步骤

修改webpack的output配置,将libraryTarget改为"commonjs2":

module.exports = {
    output: {
          path: __dirname,
          filename: "dist/index.js",
          libraryTarget: "commonjs2", // 替换原有的"var"
          jsonpFunction: "webpack_jsonp_gbundles"
    },
    // 其余配置保持不变
}

原理说明

commonjs2是npm模块通用的导出格式,webpack会将你的默认导出组件直接赋值给module.exports,这样其他项目通过import导入时,就能直接获取到组件函数,而非包含默认导出的对象。

如果修改后仍有问题,可以额外添加libraryExport: 'default'强制指定导出默认内容:

output: {
  // ...其他配置
  libraryTarget: "commonjs2",
  libraryExport: 'default'
}

验证方式

重新打包后,查看dist/index.js的末尾,应该能看到类似module.exports = MyPromosComponent;的代码,而非全局变量赋值语句。此时再在其他项目中导入组件,就能正常渲染了。

内容的提问来源于stack exchange,提问作者pesho hristov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 17:35:05