使用index.js从'/ folder'导入javascript
我注意到有几个案例我见过以下内容:
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...
}
注意我们调用的最后一个文件从'./reducers'中导入masterReducer
- 有些人似乎认为这应该导入 index.js文件中的默认导出
。
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.
这实际上是规范的一部分? - 我的解释/问题是,这是许多人使用WebPack v1的结果,它将 import
语句翻译成CommonJS风格的需要
陈述?或者这将在WebPack v2中以官方 import
/ export
支持?
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?
这实际上是规范的一部分吗?
Is this actually part of the specification?
没有。如何将模块标识符(在您的情况下为'./ reducers'
)解析为实际模块,由模块加载器/捆绑器实现,而不是由ES6指定。它似乎也没有在 CommonJs 中指定。
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.
这就是节点的工作方式 - 当需要一个目录时,它将使用 index.js
文件。像 browserify 或 webpack 遵循此约定(出于比较原因)。
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).