关于typescript的命名空间和模块循环嵌套问题。

目的。我是希望有一些公共的方法能够在很多地方方便的调用到,不必一个个引入。

比如能像这样:

app.kits.toast("")
app.logger.log("")
app.http.send(“xxx.com”)
这样使用

。我的代码大概是这样写的。
1.kits.ts
export namesapce KITS{
export function toast(){
let toast = new Toast()
toast.show()
}
}

2.logger.ts …

3.app.ts
import {LOGGER} from “./logger”
import …

export namespace app{
export let kits = KITS
export let logger = LOGGER
}

4.Toast.ts
import {app} from “./app”
import {logger} from “./logger”

export class Toast{
show(){
app.logger.log(“show”); //这里会报logger是空。
//logger.log(“show”); //这样就没有问题。
}
}

也就是说我定义了多个模块,分别有不同的功能。 但我想有一个类似全局变量的东西把这些全引入进来,这样别的地方在用的时候只需要引用这一个就够了。
可好像在循环引用的时候总会出出未定义的问题。

比如上面的app.logger.log() 运行时就会提示logger为空。

可是在别的地访, 比如某个scene里的某段 代码里又是能用到app.logger的。

我在vs里单独建个项目写类似的代码,然后用tsc编译为js,再用node去运行,却没有这样的问题。

求支招。:joy:

app.ts

export * from "./module1"
export * from "./module2"
export * from "./module3"

http://docs.cocos.com/creator/manual/zh/scripting/typescript.html

这里有creator中typescript脚本的命名空间使用说明,也能对你的问题有帮助。

我按照这个试了。vs编译报错,大概意思是说在使用commonjs时不能使用outputfile

这样别人使用时就是

import {m1, m2, m3} from “app”

m1.xxx()
m2.xxx(0

我希望用的时候是
import app from “app”

app.m1.xxx()
app.m2.xxx()

好纠结。

m1.ts

export const method1 = () => { return 1 }
export default () => { return 2 }
export const method3 = () => { return 3 }

app.ts

export {
    method1,
    method3 as method4,
    default as method2,
} from "./m1"

usage.ts

import * as app from "./app"
app.method1()
app.method2()
app.method4()

如果不怕麻烦可以先import再export

app.ts

import {
    method1,
    method3,
    default as method2,
} from "./m1"

export = {
    method1,
    method2,
    method4: method3
}