[英]How do dynamically instantiate using typescript's external modules
We started using requirejs for our project and converting all our internal modules to external modules. 我们开始在项目中使用requirejs并将所有内部模块转换为外部模块。
I'm having problems dynamically instanciating classes. 我在动态实例化类时遇到问题。 We need to be able to instanciate classes using a simple dot notation string.
我们需要能够使用简单的点符号字符串实例化类。
When all our modules were internal, they were accessible through the window object. 当所有模块都位于内部时,可以通过window对象访问它们。 Here's an example :
这是一个例子:
// file - TestAction.ts
module cb.action {
export class TestAction {
constructor() {}
}
}
Using the following function with className = "cb.action.TestAction" we could easily get a TestAction instance. 通过将以下函数与className =“ cb.action.TestAction”一起使用,我们可以轻松获取TestAction实例。
var instantiateByName = function (className) {
"use strict";
var ClassName2 = className.split('.').reduce(function (current, name) {
return current[name];
}, window);
return new ClassName2();
};
Now that we changed all our modules to external modules the TestAction.ts file now looks like this : 现在,我们将所有模块更改为外部模块,TestAction.ts文件现在看起来像这样:
// file - TestAction.ts
export class TestAction {
constructor() {}
}
2 main problems : - Depending on the dot notation string I'm receiving, I need to import a different file. 2个主要问题:-根据接收的点符号字符串,我需要导入其他文件。 ( dynamically require a file ) - I need an equivalent to the instantiateByName function above since I can't use the window object anymore.
(动态需要一个文件)-我需要与上面的InstantiateByName函数等效的函数,因为我不能再使用window对象了。
Looking forward to having your inputs 期待您的意见
I would slightly change the module structure (if you are using one class per file...) 我会稍微改变模块结构(如果每个文件使用一个类...)
class TestAction {
constructor() {}
}
export = TestAction;
And then instead of using a method to dynamically load modules by name, you can use RequireJS iteself to do it... 然后,可以使用RequireJS iteself来代替按名称动态加载模块的方法...
// Instead of 'instantiateByName'...
import TestAction = require('./action/TestAction');
var myAction = new TestAction();
This is compiled into the following... 这被编译为以下内容...
define(["require", "exports", './action/TestAction'], function(require, exports, TestAction) {
var myAction = new TestAction();
});
And this handles the fact that RequireJS loads the script file asynchronously. 这可以处理RequireJS异步加载脚本文件的事实。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.