【问题标题】:React | Npm package - How can I export 2 components for use as an npm package反应 | Npm 包 - 如何导出 2 个组件以用作 npm 包
【发布时间】:2019-09-09 04:08:22
【问题描述】:

所以这可能是一个愚蠢的问题,但它一直困扰着我一段时间。

使用 React,我创建了两个组件(Buttons.js 和 Message.js),每个组件都有一个导出。但是,现在我希望将这两个组件都用作 npm 包。我已经使用一个没有问题的示例测试了我的组件,然后我毫不费力地发布了我的 npm 包。但是现在我尝试使用导入和渲染我的组件,我偶然发现了一个错误。

问:如何导出 2 个组件以用作 npm 包

这是我的方法:

我的包裹

Buttons.js

import React from "react";
import "./Buttons.css";

export const Button = ({ text }) => <div className="button">{text}</div>

Message.js

import React from 'react';
import "./Message.css";

export const Message = ({ type, message }) => <div className={["messageBox", type].join(" ")}>{message}</div>

index.js

export { default as Buttons } from "./Buttons";
export { default as Message } from "./Message";

Package.json

{
   "name": "ui-elements",
   "version": "1.0.0",
   "description": "Just a test",
   "main": "dist/index.js"
...
}

我的项目

import Message from "ui-elements";
import Button from "ui-elements";

export default class App extends Component  {
    render () {
        return (
            <React.Fragment>
                <Button text="Log in"  />
                <Message type="error" message="Error, awesome..." />
            </React.Fragment>
        )
    }
}

错误信息

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

【问题讨论】:

  • 如果您将它们发布到 npm 包中,为什么要将它们引用为相对路径?不应该是npm install ui-elements,然后是import { Message, Buttons } from "ui-elements"
  • 我已经更新了我的问题。我像您提到的那样将它们更改为“ui-elements”;但它仍然给我上述错误。
  • 你有 2 个不同的出口......这就是你的问题。检查 0xnoob 答案。

标签: javascript node.js reactjs npm package


【解决方案1】:

在你的 index.js 中试试这个:

import Buttons from "./Buttons";
import Message from "./Message";

export {
  Buttons,
  Message
}

但我认为 ES6 模块在 node.js 中仍处于试验阶段,因此可能需要将其重写为旧的 module.exports 版本:

const Buttons = require("./Buttons"); // and rewrite in Buttons.js
const Message = require("./Message"); // and rewrite in Message.js
module.exports = { 
  Buttons, 
  Message 
};

【讨论】:

  • 感谢您的回答,问题解决了 =) ES6 方式对我来说效果很好。谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-09-22
  • 2018-09-10
  • 2020-03-16
  • 2017-01-30
  • 2016-07-09
  • 2018-02-15
  • 2021-10-06
  • 1970-01-01
相关资源
最近更新 更多