【发布时间】:2017-10-30 17:15:05
【问题描述】:
我正在尝试从一个 .ts 文件导出命名空间并从另一个 .ts 文件导入并收到错误 NewMain.ts:2 Uncaught ReferenceError: require is not defined。我是新手,实际上正在学习 TypeScript。这是我的tsconfig.json 文件
{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true
},
"files": [
"greeter.ts",
"Main.ts",
"RajIsh.ts",
"NewMain.ts"
],
"exclude": [
"node_modules"
]
}
这是我的NewMain.ts,我在其中导入名称空间
import {DepartmentSection} from "./RajIsh"
class Employee{
name: string;
//Function
Display(username:string)
{
this.name=username;
console.log(this.name);
}
}
var person = new Employee();
var itCell= new DepartmentSection.ITCell("Information Technology Section");
console.log("Displaying from NewMain.ts by importing......");
console.log(person.Display("XYZ")+" belongs to "+ itCell.DisplaySectionName("Finance Revenue and Expenditure Section"));
console.log("Wooooooooo Hurrey!!!!!!!!!!!!!!!......");
这是我在RajIsh.ts中的命名空间
export namespace DepartmentSection {
export class Section {
//===================Class Property by default public
name: string;
//==================Constructor of Section Class taking parameter of Employee Name
constructor(theName: string) {
this.name = theName;
}
//====================Function which displays the department name of a person
Department(depatmentName: string = "") {
console.log(`${this.name} , ${depatmentName} !!`);
}
}
//============================================================================================
//=========================Inheritance
export class ITCell extends Section{
constructor(SectionName: string) {
super(SectionName);
}
DisplaySectionName(DepartmentName:string) {
console.log("Printing Section name...");
super.Department(DepartmentName);
}
}
export class LoanAndAccount extends Section {
constructor(SectionName: string) {
super(SectionName);
}
DisplaySectionName(DepartmentName:string) {
console.log("Printing another Section name...");
super.Department(DepartmentName);
}
}
}
我哪里做错了?我也尝试像这样导入import DepartmentSection = require('./RajIsh');,但是当我尝试访问类和函数时,它会抛出一个错误,说Property 'ITCell' does not exist on type 'typeof' RajIsh。我需要做什么?
【问题讨论】:
-
您是否尝试过只导出类而不使用命名空间?通过删除这一行
export namespace DepartmentSection并在 ts 文件中导入单个类 -
它在这一行中抛出错误
Uncaught ReferenceError: define is not defineddefine("RajIsh", ["require", "exports"], function (require, exports) -
您在寻找模块还是命名空间?因为您遵循 ES6 typescrpt 中模块的导入样式
-
我正在寻找命名空间....
-
在使用命名空间时不必使用
export和import。相反,您可以只在一个文件中使用namespace Test { class Thing },然后在另一个文件中您可以通过let n = new Test.Thing()使用该类。不需要模块捆绑器。
标签: typescript npm