简体   繁体   中英

Error while creating a npm module of a react component

I am trying to create a node module for all the reusable react components that i have. I am stuck while importing a jsx file. I have a basic jsx module ie greeting.jsx in components folder.

//greeting.jsx
import React from 'react';
export default class Greeting extends React.Component {
    render() {
        return (
            <p>Hello World</p>
        )
    }
}

Folder structure :-

- index.js
- components
  ¦-- Greeting
      ¦-- greeting.jsx
  ¦-- <Other Modules like Greeting>

index.js which imports all the components and exports them

//index.js

import Greeting from './components/Greeting/greeting.jsx';

export default {
    Greeting
};

When i have to use greeting module i have to import the module. Like the way in below code. But doing this gives me error on the page

import React from 'react';
import ReactDOM from 'react-dom';
import GreetingModule from './index.js';

ReactDOM.render( <GreetingModule />, document.getElementById('content') );

Errors:-

warning.js:45 Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).
invariant.js:39 Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

This is where i am stuck now. Although if i import jsx file directly (like below) then it works.

import React from 'react';
import ReactDOM from 'react-dom';
import GreetingModule from './components/Greeting/greeting.jsx';

ReactDOM.render( <GreetingModule />, document.getElementById('content') );

But this is not the way i want to do as i am trying to create a npm module and my index.js should export all the react components.

I have tried googling for creating a npm module for react componets but couldn't find any thing. Please Help, in resolving the issue

The problem is that you are running a babel transform on module in isolation.

I bet that your index.js after transform looks something like:

var Greeting = require('./components/Greeting/greeting.jsx');

exports.default = {
  Greeting
};

And here lies the problem. Your module is exporting all its meat under the default property. So a person using your module needs to use it as follows:

var Greeting = require('greeting').default;

You may either live with this, or use the old way of exporting modules in your index.js. So, you'd change only your index.js to this:

//index.js

import Greeting from './components/Greeting/greeting.jsx';

module.exports = {
  Greeting
};

That should do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM