-
-
Save knowbody/754c3cc0462ed81d913fdff3c32eb4e0 to your computer and use it in GitHub Desktop.
| // components/Bar.js | |
| import { doSomething } from '../actions'; | |
| // ... | |
| // this.props.dispatch(doSomething()); |
| // actions/foo.js | |
| function doSomething() { | |
| return { | |
| type: 'DO_SOMETHING', | |
| }; | |
| } | |
| export default { | |
| doSomething | |
| }; |
| // actions/index.js | |
| import fooActions from './foo'; | |
| module.exports = { | |
| ...fooActions | |
| }; | |
| /* Why not? | |
| * export default { | |
| * ...fooActions | |
| * } | |
| */ |
Oh, you're also re-exporting:
// foo.js
export * from './Bar'
// if you want to re-export other stuff
export * from './Baz'What ryan said. My thinking is that you don't want to have to repeat yourself in the index.js file because that would be annoying. Here's what I suggest:
// components/Bar.js
import { doSomething } from '../actions';
// ...
// this.props.dispatch(doSomething());// actions/foo.js
export function doSomething() {
return {
type: 'DO_SOMETHING',
};
}
// alternatively, you could put this at the bottom or the top of the file. I prefer to keep all my exports in one place so if you export multiple things I'd recommend doing it like this.
// export {doSomething};// actions/index.js
export * from './foo'; // look mah, I don't have to repeat myself! :D
// alternatively, if ./foo did `export default function doSomething()` then you could do:
// export {default as foo} from './foo'ES6 modules are confusing. I gave a talk about them that might be helpful:
Good luck!
ES6 modules are confusing
...when you expect them to work like common-js modules.
basically what I want to achieve is to be able to import any action in my component like:
import { someFunc } from '../actions';so I don't need to do stuff like:
import { someFunc } from '../actions/foo';Yeah, if you do what Ryan and I suggest with export * from './foo' then you can do that.
👍 thank you! @ryanflorence @kentcdodds
Do you need any particular Babel/Webpack configuration (on top of the es2015 Babel preset) to use export * from './foo'? I've hit this exact problem in a project and can't seem to get the re-exporting part to work.
Why not? Because the
{ }doesn't mean "an object", much like the{inif () {}doesn't mean that. It means "I'm gonna export some stuff by statically analyzable names so that browsers and bundlers can optimize the whole thing", like tree-shaking, etc. I'm sure there are other reasons.All you really need to do is: