我正試圖通過字符串動態地從模塊實例化一個類。通過字符串導出參考模塊
說我有./src/main.ts
,./src/role/index.ts
和./src/role/role<n>.ts
在./src/role/index.ts
:
export * from './role1.ts'
export * from './role2.ts'
和示例作用./src/role/role1.ts
export class Role1 {
constructor() { }
}
然後從我的主,我想要做的事像
import * as Roles from './role'
function load_role(to_load: string) {
for(let role in Roles) {
if(role == to_load) // e.g. Role1
return Roles[role]()
}
}
避免的笨拙如:
import * as Roles from './role'
function load_role(to_load: string) {
if(to_load == 'Role1')
return Roles.Role1()
else if(to_load == 'Role<n>')
return Roles.Role<n>()
}
但我不能串引用角色模塊,這可能嗎?
能你分享了roleN.ts的內容 –