使用 index.js 从“/文件夹”导入 javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35442174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript import from '/folder' with index.js
提问by Jordan
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.
注意我们调用的最后一个“文件” import masterReducer from './reducers'
——有些人似乎认为这应该default export
从 index.js 文件中导入。
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?
这实际上是规范的一部分吗?- 我的解释/问题是,这是许多人使用 WebPack v1 将import
语句转换为 CommonJS 样式requires
语句的结果?或者这会在具有“官方” import
/export
支持的WebPack v2 中中断吗?
回答by Bergi
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 CommonJseither.
不。模块标识符('./reducers'
在您的情况下)如何解析为实际模块由模块加载器/捆绑器的实现决定,ES6 没有具体说明。而且它似乎也没有在CommonJs中指定。
This is just how node does it - when requiring a directory, it's index.js
file will be used. Bundlers like browserifyor webpackfollowed this convention (for compat reasons).
这就是节点的工作方式 - 当需要目录时,index.js
将使用它的文件。像捆扎机browserify或的WebPack遵循了这一约定(compat的原因)。