使用 index.js 从“/文件夹"导入 javascript [英] 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...
}
注意最后一个文件"我们调用 import masterReducer from './reducers'
- 有些人似乎认为这应该从 index.js 文件中导入 default export
.
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 样式的 requires
语句?或者这是否会在 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.
这就是 node 的工作方式 - 当需要一个目录时,将使用 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).
这篇关于使用 index.js 从“/文件夹"导入 javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!