我有一些代码:
baseTypes.ts
export namespace Living.Things {
export class Animal {
move() { /* ... */ }
}
export class Plant {
photosynthesize() { /* ... */ }
}
}
Run Code Online (Sandbox Code Playgroud)
dog.ts
import b = require('./baseTypes');
export namespace Living.Things {
// Error, can't find name 'Animal', ??
export class Dog extends Animal {
woof() { }
}
}
Run Code Online (Sandbox Code Playgroud)
tree.ts
// Error, can't use the same name twice, ??
import b = require('./baseTypes');
import b = require('./dogs');
namespace Living.Things {
// Why do …Run Code Online (Sandbox Code Playgroud) 我是打字稿的新手,我正在为WebGl编写一个小型的原型框架.我正在重构我的项目,并遇到了一些问题,如何组织我的项目,因为(模块和命名空间)方法似乎都有严重的缺点.
这篇文章不是关于如何使用这些模式,而是如何克服这些模式带来的问题.
来自C#,这似乎是最自然的方式.每个类/模块都获得它适当的命名空间,我在tsconfig.json中提供"outFile"参数,因此所有内容都连接成一个大文件.编译后,我将根命名空间作为全局对象.依赖项没有内置到项目中,所以你手动必须在你的html中提供所需的*.js文件(不好)
示例文件
namespace Cross.Eye {
export class SpriteFont {
//code omitted
}
}
Run Code Online (Sandbox Code Playgroud)
示例用法(通过在html中提供js文件,您必须确保将Cross命名空间加载到全局命名空间中)
namespace Examples {
export class _01_BasicQuad {
context: Cross.Eye.Context;
shader: Cross.Eye.ShaderProgram;
//code omitted
}
}
Run Code Online (Sandbox Code Playgroud)
对于大多数项目,我们建议使用外部模块并使用命名空间进行快速演示和移植旧的JavaScript代码.
来自https://basarat.gitbooks.io/typescript/content/docs/project/namespaces.html
Typescript支持ES6模块,它们是新的和有光泽的,每个人似乎都认为它们是要走的路.这个想法似乎是每个文件都是一个模块,通过在import语句中提供文件,你可以非常明确地定义你的依赖关系,这使得捆绑工具很容易有效地打包你的代码.我大多数每个文件有一个类似乎与dhte模块模式不兼容.
这是重构后的文件结构:

此外,我在每个文件夹中都有一个index.ts文件,因此我可以导入其所有类 import * as FolderModule from "./folder"
export * from "./AggregateLoader";
export * from "./ImageLoader";
export * from "./TiledLoader";
export * from "./XhrLoaders";
export * from "./XmlSpriteFontLoader";
Run Code Online (Sandbox Code Playgroud)
示例文件 - 我认为问题在这里变得清晰可见.. …
我是打字稿的初学者,我已经阅读了很多关于打字稿和单身人士的文章,我仍然可以使用它.
我有同样的问题: Node.js和Typescript Singleton模式:看起来单身用户之间不共享singleton.
我也读过这篇文章:https://fullstack-developer.academy/singleton-pattern-in-typescript/ 和这一篇:http://www.codebelt.com/typescript/typescript-singleton-pattern/
最后,当我从一个模块转到另一个模块时,它看起来像我的单例类始终处于默认状态.在调用时getInstance(),因为值设置为new Path()对我来说似乎很明显,单例始终处于默认状态,但在许多源中(如前两个提供的那样)是这样做的方法.
我究竟做错了什么 ?谢谢.
这是我的单身人士(Path.ts):
class Path{
private static _instance: Path = new Path();
private _nodes: NodeModel[];
private _links: LinkModel[];
public static getInstance(): Path{
if(Path._instance)
return Path._instance;
else
throw new Error("Path is not initialized.");
}
public setPath(nodes: NodeModel[], links: LinkModel[]){
this._nodes = nodes;
this._links = links;
}
public nodes(){ return this._nodes; }
[...]
}
export = Path;
Run Code Online (Sandbox Code Playgroud)
PathDefinition.ts
module PathDefinition{
export function defaultDefinition(){ …Run Code Online (Sandbox Code Playgroud)