JavaScript对应于Python的__init__.py文件

8

在Python中,为了在一个包中暴露顶层功能,需要创建一个__init__.py文件。

#__init__.py
from .implmentation import impl_function

def exposed_fn():

  """call impl_function

在导入一个目录(包)时,使用exposed_fn作为主要函数暴露出来。在javascript的require中,这个等价于什么?

显然可以这样做。

//init.js?
var impl_function = require('./implmentation.js').impl_function;

var exposed_fn = function () {//call impl_function ...};

//Will expose `exposed_fn` when requiring this file.
module.exports = {
  exposed_fn: exposed_fn
}

//How to expose `expose_fn` when requiring a this folder?????

有相应的替代品吗?到目前为止,所有的搜索都没有取得成果。

1个回答

12
使用相同的方式在index.js文件中似乎也可以工作。如果从index.js文件导出对象,则可以在文件夹级别访问它们。

index.js 中是否有类似于 __all__=['some_module'] 的等效方式来定义命名空间,就像在 __init__.py 中所做的那样? - tutuca

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接