Typescript - 内部模块中的导入声明不能引用外部模块
Posted
技术标签:
【中文标题】Typescript - 内部模块中的导入声明不能引用外部模块【英文标题】:Typescript - import declarations in an internal module cannot reference an external module 【发布时间】:2015-08-11 06:14:30 【问题描述】:在 VSCode 中练习 TypeScript、开发 Todo 应用程序、尝试导入“todo”模块时,vscode 智能感知生成错误: 内部模块中的导入声明不能引用外部模块 控制台也抛出错误:"TodoApp is not defined"
请问有人可以帮忙吗?我认为结构不正确,但似乎无法纠正。最终我的目标是让 .ts 文件,最好全部编译成一个 js 文件“testApp.js”。
这是我的代码:
task.ts
module TodoApp
export enum TaskType FrontEnd, BackEnd, Designer ;
interface Itask
Name: string;
Description: string;
TaskType: TaskType;
Completed: boolean;
export class Task implements Itask
Name: string;
Description: string;
Completed: boolean = false;
TaskType: TaskType;
constructor(Name: string, Description: string, TaskType: TaskType)
this.Name = Name;
this.Description = Description;
this.TaskType = TaskType;
todo.ts
///<reference path="task.ts" />
///<reference path="../typings/jquery/jquery.d.ts" />
module TodoApp
"use strict"
interface IJson
interface ITaskManager
Tasks: Task[];
GetTasks(t: any[]): void;
AddTask(t: Task): void;
UpdateTask(n: string, d: string, tt: TaskType): void;
DeleteTask:
(i: number): void;
(i: Task): void;
export class TaskManager implements ITaskManager
public Tasks = new Array<Task>();
constructor()
GetTasks(d: any[])
public AddTask(_task: Task)
this.Tasks.push(_task);
UpdateTask(_name: string, _desc: string, _taskType: TaskType)
DeleteTask(i: any)
if (typeof i === typeof Task)
//delete object
else
//delete task of index
testApp.ts
module TestApp
import TodoApp = require("todo"); ///<< error occurs here
export class ControlTodoApp
static Start()
window.onload = function(e)
var tm = new TodoApp.TaskManager();
var task = new TodoApp.Task("MyTask", "Task Description", TodoApp.TaskType.Designer);
tm.AddTask(task);
console.log(tm.Tasks);
var ca = new TestApp.ControlTodoApp.Start();
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
</head>
<body>
<div class="container">
<div class="inner">
<div class="img-cont">
<img src="assets/images/myimg.png" />
</div>
</div>
<div class="content"></div>
</div>
<script src="assets/js/default/jquery.min.js"></script>
<script src="assets/js/ts/testApp.js"></script>
</body>
</html>
【问题讨论】:
【参考方案1】:你结合commonjs and amd in code,使用其中之一
testApp.ts
///<reference path="task.ts" />
///<reference path="todo.ts" />
或
testApp.ts
module TestApp
import TaskManager = require("todo");
import TaskType = require("task");
export class ControlTodoApp
static Start()
window.onload = function(e)
var tm = new TaskManager.TaskManager();
var task = new TaskType.Task("MyTask", "Task Description", TaskType.TaskType.Designer);
tm.AddTask(task);
console.log(tm.Tasks);
task.ts
export = TodoApp;
module TodoApp
...
todo.ts
export = TodoApp;
module TodoApp
...
【讨论】:
嗨 Madreason,感谢您的反馈。我让它在 testApp.ts 中应用引用... ///以上是关于Typescript - 内部模块中的导入声明不能引用外部模块的主要内容,如果未能解决你的问题,请参考以下文章
从模块导入“私有”TypeScript 声明而不通过 package.json 公开它