簡體   English   中英

使用 Webpack 4 構建 React 組件庫

[英]Build React components library with Webpack 4

我目前正在構建一個 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 配置中遺漏了一些東西,或者其中一個屬性可能有問題,但是在閱讀了多篇文章和教程后,我不知道是哪一個。

您將庫導出為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/

我要做的是將您的組件導出為默認值,然后重新導出為index.js命名的:

/// Button.js
import React from "react";

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

export default Button ;
// index.js
export { default as Button } from "./src/components/Button";

然后你可以做

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

還要確保您在設計系統的package.json main設置,指向您的index.js

此外,如果您仍然希望在某些組件中使用命名導出,您可以從該組件文件中導出所有內容:

//index.js
export * from "./src/components/ComponentWithNamedExports";

無論哪種方式,您都將確保所有組件始終有一個導出點。

編輯:如libraryTarget Syed Adeeb 所述,您的配置中有錯誤的libraryTarget 我會從那里刪除libraryTargetlibrary

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM