使用 Webpack 4 构建 React 组件库 [英] Build React components library with Webpack 4

查看:70
本文介绍了使用 Webpack 4 构建 React 组件库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently building a library of React components and bundling it with Webpack 4.

从构建库的包到在 npm 注册表上发布它,一切都很好.

Everything works just fine from building the library's bundle to publishing it on an npm registry.

但是,我无法在其他 React 应用程序中导入它的任何组件并在运行时收到此错误消息:

But then, I'm not able to import any of its components in an other React application and get this error message at runtime:

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

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

这是相关的代码:

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

A dumb component from my components library: 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:

My Webpack config 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: ""
  }
};

最后,在另一个应用程序中导入这个组件:

And finally, the import of this component in an other application:

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

我想我的 Webpack 配置中遗漏了一些东西,或者其中一个属性可能有问题,但是在阅读了多篇文章和教程后,我不知道是哪一个.

I guess I'm missing something in my Webpack config or one of the property may be wrong, but after reading multiple posts and tutorials, I can't figure which one.

推荐答案

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

You're exporting your library as commonjs and trying to import it via import/export syntax. You should change your output to

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

在这里找到了很多信息:https://webpack.js.org/guides/作者图书馆/

Found a lot of info here: https://webpack.js.org/guides/author-libraries/

这篇关于使用 Webpack 4 构建 React 组件库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆