使用index.js从'/ folder'导入javascript

时间:2020-12-04 23:58:43

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.

注意我们从'./reducers'调用import masterReducer的最后一个“文件” - 有些人似乎认为这应该从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将导入语句转换为CommonJS样式的需求语句的结果?或者这将在WebPack v2中以“官方”导入/导出支持中断?

1 个解决方案

#1


47  

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.

否。模块标识符(在您的情况下为'./reducers')如何解析到实际模块是由模块加载器/捆绑器实现的,它不是由ES6指定的。它似乎也没有在CommonJs中指定。

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文件。像browserify或webpack这样的捆绑包遵循这个约定(出于compat的原因)。

#1


47  

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.

否。模块标识符(在您的情况下为'./reducers')如何解析到实际模块是由模块加载器/捆绑器实现的,它不是由ES6指定的。它似乎也没有在CommonJs中指定。

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文件。像browserify或webpack这样的捆绑包遵循这个约定(出于compat的原因)。