小编典典

使用Webpack 4构建React组件库

reactjs

我目前正在构建一个React组件库,并将其与Webpack 4捆绑在一起。

从构建库的捆绑包到将其发布到npm注册表中,一切工作都很好。

但是,然后,我无法将其任何组件导入其他React应用程序中,并在运行时得到以下错误消息:

元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件),但得到:未定义。您可能忘记了从定义文件中导出组件,或者可能混淆了默认导入和命名导入。

这是相关的代码:

我的组件库中的一个哑组件: button/index.js

import React from "react";

const Button = () => <button>Foobar</button>;

export { Button };

我图书馆的主要入口index.js

import { Button } from "./src/components/Button";

export { Button };

我的Webpack配置webpack.config.js

const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
  entry: "./index.js",
  plugins: [new CleanWebpackPlugin()],
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  },
  output: {
    filename: "index.js",
    path: path.resolve(__dirname, "dist"),
    libraryTarget: "commonjs",
    library: ""
  }
};

最后,将该组件导入另一个应用程序:

import { Button } from "my-design-system";

我想我的Webpack配置中缺少某些内容,或者其中一个属性可能是错误的,但是在阅读了多个帖子和教程之后,我无法弄清楚哪一个。


阅读 463

收藏
2020-07-22

共1个答案

小编典典

您正在将库导出为,commonjs并尝试通过import/export语法导入它。您应该将输出更改为

output: {
  filename: "index.js",
  path: path.resolve(__dirname, "dist"),
  libraryTarget: "umd",
  library: "my-design-system"
}

在这里找到了很多信息:https :
//webpack.js.org/guides/author-
libraries/

2020-07-22