依赖注入库-重命名注入值 [英] Dependency injection library - renaming injected values

查看:75
本文介绍了依赖注入库-重命名注入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按名称插入lodash,如下所示:

I'd like to inject lodash by name, something like this:

let val = function(lodash){
   // lodash will be injected, simply by using require('lodash');
};

但是说我想重命名导入,我想做这样的事情:

but say I want to rename the import, I want do something like this:

let val = function({lodash:_}){

};

let val = function(lodash as _){

};

是否可以用ES6 / ES7 / ES8或TypeScript做到这一点?

is there a way to do this with either ES6/ES7/ES8 or TypeScript?

请注意,此DI框架所做的工作不只是require('x')...它将尝试首先注入其他值,如果不存在其他值,则它将尝试要求

Note that this DI framework does more work than just require('x')...it will try to inject other values first, if nothing else exists, then it will attempt to require the value.

请注意,这里的要求是,当您调用val.toString()时, lodash将被视为参数名称。但是在运行时会在函数体内看到_而不是lodash。这是因为为了注入lodash,我们调用fn.toString()来获取参数名称。

推荐答案

更新



此处是的链接npm软件包 di-proxy (受此答案启发),具有100%的代码覆盖率,并支持备注以提高性能,与Node.js <$ c兼容$ c>> = 6.0.0 。

这里我在修改时发现的一个很棒的解决方案对象解构 代理

Here's an awesome solution I figured out while tinkering around with object destructuring and Proxy:

/* MIT License */
/* Copyright 2017 Patrick Roberts */
// dependency injection utility
function inject(callbackfn) {
  const handler = {
    get(target, name) {
      /* this is just a demo, swap these two lines for actual injection */
      // return require(name);
      return { name };
    }
  };
  const proxy = new Proxy({}, handler);

  return (...args) => callbackfn.call(this, proxy, ...args);
}

// usage

// wrap function declaration with inject()
const val = inject(function ({ lodash: _, 'socket.io': sio, jquery: $, express, fs }, other, args) {
  // already have access to lodash, no need to even require() here
  console.log(_);
  console.log(sio);
  console.log($);
  console.log(express);
  console.log(fs);
  console.log(other, args);
});

// execute wrapped function with automatic injection
val('other', 'args');

.as-console-wrapper {
  max-height: 100% !important;
}

通过对象分解将参数传递给函数会为对象文字上的每个属性调用getter方法,以便在执行函数时确定值。

Passing parameters to a function via object destructuring invokes the getter methods for each property on the object literal in order to determine the values when the function is executed.

被解构的对象初始化为 Proxy ,您可以拦截每次获取方法的调用,并引用尝试解析的属性名称,并返回您选择用来解决它的值用。在这种情况下,解析度应为 require(name),仅通过在函数对象参数中将其指定为属性名称即可注入模块。

If the object being destructured is initialized as a Proxy, you can intercept each getter invocation with a reference to the property name attempting to be resolved, and return a value you choose to resolve it with. In this case, the resolution should be the require(name), which injects the module just by specifying it as a property name in the function object parameter.

下面是一个演示的链接,您可以在其中实际看到它在Node.js中的工作。

Below is a link to a demo where you can actually see it working in Node.js.

尝试

下面是该演示中的代码,仅供参考,因为它在更大程度上展示了对象分解的作用:

Here's the code in that demo just for reference, because it demonstrates object destructuring to a larger degree:

/* MIT License */
/* Copyright 2017 Patrick Roberts */
// dependency injection utility
function inject(callbackfn) {
  const handler = {
    get(target, name) {
      return require(name);
    }
  };
  const proxy = new Proxy({}, handler);

  return (...args) => callbackfn.call(this, proxy, ...args);
}

// usage

// wrap function declaration with inject()
const val = inject(function ({
  fs: { readFile: fsRead, writeFile: fsWrite },
  child_process: { fork: cpF, spawn: cpS, exec: cpE },
  events: { EventEmitter }
}, other, args) {
  // already have access to modules, no need to require() here
  console.log('fs:', { fsRead, fsWrite });
  console.log('child_process:', { fork: cpF, spawn: cpS, exec: cpE });
  console.log('EventEmitter:', EventEmitter);
  console.log(other, args);
});

// execute wrapped function with automatic injection
val('other', 'args');

如上所述,我已经发布了一个完整的npm包来实现这一概念。我建议您检查一下是否喜欢这种语法,并希望它比这个非常基本的示例更具性能和测试能力。

As stated above, I have published a full npm package implementing this concept. I recommend you check it out if you like this syntax and want something a little more performant and tested than this very basic example.

这篇关于依赖注入库-重命名注入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆