Reputation: 1555
So this might be a silly question, but it keeps bugging me for a while now.
Using React, I have created two components (Buttons.js & Message.js), each with an export. However, now I wish to use both of these components as a npm package. I have tested my components using an example without a problem, I then published my npm package without a sweat. But now that I try to use import and render my components, I stumbled on an error.
Q: How can I export 2 components for use as an npm package
This is my approach:
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>
)
}
}
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.
Upvotes: 1
Views: 2267
Reputation: 1037
Try this in your index.js:
import Buttons from "./Buttons";
import Message from "./Message";
export {
Buttons,
Message
}
But I think ES6 modules are still experimental in node.js, so it could be that you have to rewrite it to the old module.exports
version:
const Buttons = require("./Buttons"); // and rewrite in Buttons.js
const Message = require("./Message"); // and rewrite in Message.js
module.exports = {
Buttons,
Message
};
Upvotes: 3