Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript import from '/folder' with index.js

I've noticed a few cases where I've seen something like the following:

// /reducers/reducer1.js export default function reducer1(state = {}, action){   // etc... }    // /reducers/reducer2.js export default function reducer2(state = {}, action){   // etc... }  // /reducers/index.js import { combineReducers } from 'redux'; import reducer1 from './reducer1'; import reducer2 from './reducer2';  export default combineReducers({   reducer1,   reducer2 })    // /store.js import masterReducer from './reducers';  export default function makeStore(){   // etc... } 

Notice the last "file" where we call import masterReducer from './reducers' - A few people seem to believe this should import the default export from the index.js file.

Is this actually part of the specification? - my interpretation/question is that this is the result of many folks using WebPack v1 which translates import statements into CommonJS-style requires statements? Or will this break in WebPack v2 with "official" import/export support?

like image 568
Jordan Avatar asked Feb 16 '16 20:02

Jordan


1 Answers

Is this actually part of the specification?

No. How module identifiers ('./reducers' in your case) are resolved to the actual modules is left to the implementation of the module loader/bundler, it's not specificed by ES6. And it doesn't seem to be specified in CommonJs either.

This is just how node does it - when requiring a directory, it's index.js file will be used. Bundlers like browserify or webpack followed this convention (for compat reasons).

like image 104
Bergi Avatar answered Sep 22 '22 02:09

Bergi