javascript import from '/folder' with index.js

JavascriptEcmascript 6Webpack

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

> 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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJordanView Question on Stackoverflow
Solution 1 - JavascriptBergiView Answer on Stackoverflow