从多个构造函数调用中通用读取参数 [英] Generic reading of arguments from multiple constructor calls
问题描述
可接受的解决方案允许我通过定义一个捕获并公开参数的包装器类来将参数传递给构造器,但这给我留下了为n
构造器使用n
包装器的问题.
The accepted solution allows me to get arguments passed into a constructor by defining a wrapper class that captures and exposes the arguments, but this leaves me with the problem of having n
wrappers for n
constructors.
有没有办法让1个函数/包装器/什么对任何数量的构造函数都适用?
Is there a way to have 1 function/wrapper/whatever that could work for any number of constructors?
我要重申的是,我将专门使用此技术来测试 Webpack插件配置,并且我希望避免为每个需要测试的插件使用单独的包装器.
I'll reiterate that I'm pursing this technique specifically to test Webpack plugin configuration, and I'd like to avoid having a separate wrapper for each plugin that I need to test.
正在寻找类似的东西
// ------------------------------------------------------------ a wrapper function?
const someWrapper = () => { /* ... */ }
const plugin1 = new Plugin({ a: 'value' })
const plugin2 = new Plugin2(arg1, arg2, { b: 'anotherValue '})
someWrapper(plugin1).args === [{ a: 'value' }]
someWrapper(plugin2).args === [arg1, arg2, { b: 'anotherValue' }]
// --------------------------------------------------------------- a wrapper class?
class Wrapper { /* ... */ }
const plugin1 = new Wrapper(Plugin, [{ a: 'value' }])
const plugin2 = new Wrapper(Plugin2, [arg1, arg2, { b: 'anotherValue '}])
plugin1.args === [{ a: 'value' }]
plugin2.args === [arg1, arg2, { b: 'anotherValue '}]
// problem with above is the wrapper is being passed to Webpack, not the underlying
// plugin; not sure yet if this would cause webpack to break or not actually
// execute the plugin as intended with a vanilla config
// ---------------------------------------------------------------- something else?
推荐答案
我能够通过对@ guest271314的建议进行修改来使它工作,即,您需要将...initArgs
传递给super()
,否则webpack将会失败与TypeError: Cannot read property '...' of undefined
.
I was able to get this working with a modification to @guest271314's suggestion, namely, you need to pass ...initArgs
to super()
, otherwise webpack will fail with a TypeError: Cannot read property '...' of undefined
.
还要考虑@terales关于确保为我的其他属性添加前缀的观点.
Also took @terales's point into account about making sure to prefix my additional properties.
const exposeConstructorArgs = (Plugin, ...args) => {
const ExposedPlugin = class extends Plugin {
constructor(...initArgs) {
super(...initArgs);
this.__initArgs__ = initArgs;
}
get __initArgs() {
return this.__initArgs__;
}
};
return Reflect.construct(ExposedPlugin, args);
};
// ...
const dllPlugin = exposeConstructorArgs(webpack.DllPlugin, {
name: '[name]',
path: path.join(buildDir, '[name].json'),
});
// ...
const pluginConfig = dllPlugin.__initArgs[0];
expect(pluginConfig.name).toEqual('[name]');
这篇关于从多个构造函数调用中通用读取参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!