简体   繁体   English

正确的ES6与子模块共享全局方式

[英]Proper es6 way of sharing global with sub-modules

I have a complex server-side node module in folder form: 我有一个文件夹形式的复杂服务器端节点模块:

store
  |-index.js
  |-accounts
      |-index.js
      |-consumer.js
      |-provider.js
  |-site
      |-index.js
      |-portal.js
  |-etc.

Where, in site/index.js I am initialising a database context that should be accessible to all sub-modules ( accounts , site , etc.) and export ing all of the sub-module interfaces, like: site/index.js我正在初始化一个数据库上下文,该上下文应可供所有子模块( accountssite等) site ,并export所有子模块接口,例如:

import dbdriver from 'mydbdriver'
import settings from './settings'

const db = dbdriver.connect(settings)

export * from '../accounts' // depends on db
export * from '../site'     // depends on db

I have considered polluting the sub-module APIs via arguments (ie requiring the context to be passed into all relevant calls), but this is ugly, IMO. 我曾考虑过通过参数污染子模块API(即要求将上下文传递到所有相关的调用中),但是IMO这很丑。

Another idea is to have an initialiser for each module that would accept the context and cash in a module-scoped global, which would be required for every single file (again, yuck.) 另一个想法是为每个模块都有一个初始化程序,该初始化程序将接受上下文并在模块范围的全局变量中兑现,这对于每个单个文件都是必需的(再次,是uck废)。

Is there a cleaner, elegant es6 way of approaching this? 有没有更干净,更优雅的ES6方法来解决这个问题?

You can do like this. 你可以这样

define db/index.js 定义db/index.js

import dbdriver from 'mydbdriver'
import settings from './settings'

const db = dbdriver.connect(settings)
export db;

and in the site/index.js 并在site/index.js

import db from  db/index
export * from '../accounts' // depends on db
export * from '../site'     // depends on db


//use db here

In this way,whenever you want to use db ,need to import the db/index 这样,无论何时要使用db ,都需要导入db/index

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM