Orboo
Orboo

Reputation: 83

Simplify React Components Import

I try to simplify my Components import, from:

import Component1 from './components/Component1'
import Component2 from './components/Component2'

To something like that:

import {Component1, Component2} from './components/'

I have tried to create an index.js file into components directory (following this post import modules from files in directory):

export * from 'Component1';
export * from 'Component2';

But I still have a "Module not found" error. Any clue ?

Thanks, Orb

Upvotes: 0

Views: 867

Answers (4)

Chase DeAnda
Chase DeAnda

Reputation: 16451

Yeah I do the same thing with my imports and it's a lot nicer when they are being exported from the same file. Here's an example of how I achieve this:

components/index.js

import Component1 from './Component1';
import Component2 from './Component2';

module.exports = {
    Component1,
    Component2
};

Then to import them

import { Component1, Component2 } from './components';

If you are using Webpack, check out webpack resolve to get rid of your relative paths.

Example using Webpack resolve

//Will work at any nested level
import { Component1, Component2 } from 'components';

And just for clarification, Component1 and Component2 should be using a default export

export default class Component1 extends React.Component {...}

or

var Component1 = createReactClass({...});
module.exports = Component1;

Upvotes: 0

Sanket Meghani
Sanket Meghani

Reputation: 905

While exporting components from your Component1 and Component2 instead of *, you should export it as objects -

//In Component1.js(x)
export { Component1 };

and

//In Component2.js(x)
export { Component2 };

With this you should be able to import like:

import { Component1 } from '...';
import { Component2 } from '...';

Upvotes: 0

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

You need to add a dot to indicate it is a local file, not an npm-published module. Change your exports line like so

export * from './Component1';

UPD To resolve next issue with named import you need to give a name to default export from Component1.js file

export Component1 from './Component1';

Follow this answer

Upvotes: 2

Dsquedo
Dsquedo

Reputation: 1

Are you sure the path is correct? Try to specify the absolute path like:

import Component1 from '/home/your_username/components/Component1' import Component2 from '/home/your_username/components/Component2'

You can see the correct path of your directory from terminal with the command "pwd".

Be sure to have the access to the directory and file. You can try to run the program as root.

Upvotes: 0

Related Questions