8

How can I bundle react-components, defined in jsx-files, in an index.js file?

In a way that the components can be accessed by import module from "/module"; let C = module.Component;.

With:

/module
  index.js
  Component.jsx
thando
  • 483
  • 2
  • 4
  • 18

3 Answers3

23

To re-export the component as a default export:

export { default } from './Component';

To re-export the component as a named export:

export { default as NamedComponent } from './Component';

You should prefer exporting as default from index.js since it will likely be the only export from the index.

Your component import will look like this:

import Component from './module';

or this, if you use a named export:

import { NamedComponent } from './module';

Assuming you're using webpack to bundle your files, to make sure your imports can use './Component' instead of './Component.jsx', include .jsx as an extension in your resolve property in webpack.config.js:

module.exports = {
  resolve: {
    extensions: ['.js', '.jsx'],
  },
};
Ryan
  • 1,372
  • 14
  • 20
1
export Component from "./Component"

You should not use export default for your use case. There is only a single default export per module. This value is to be considered as the "main" exported value since it will be the simplest to import. Refer https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export for more detail

alpha
  • 1,103
  • 7
  • 10
  • Thank you, but this is not my point here, the problem is that the index.js seems to be incompatible with the jsx files. – thando Jun 03 '16 at 13:27
  • is the code working if you replace your import and export statement with my code? – alpha Jun 03 '16 at 13:43
  • 1
    Thank you! The `index.js` as proposed [here][1] is working: `export { default as Component } from "./Component.jsx";` [1]: http://stackoverflow.com/questions/34072598/es6-exporting-importing-in-index-file – thando Jun 06 '16 at 17:19
1

Inside index.js

export { default as ComponentName } from './Component';

Then In App.js [Import it Like this]

import {ComponentName} from './module'

Fitsum Alemu
  • 359
  • 3
  • 2