导入已从TypeScript文件创建的js文件

时间:2019-05-31 11:15:41

标签: typescript

有两个Typescript文件是模块,其中一个被用作外部模块。据我了解,使用外部模块比内部模块更舒适,因为您不必每次在类之前都输入名称空间。 我的任务是:

Create modular typescript files -> Compile them into js files -> 
-> import the js files into a html page

问题是-浏览器找不到js文件的导出,但是当我在节点js编译器上尝试它时,它完全可以正常工作。

main.js:2 Uncaught ReferenceError: exports is not defined
at main.js:2
(anonymous) @ main.js:2
person.js:2 Uncaught ReferenceError: exports is not defined
at person.js:2

项目结构为:

Project
      -> main.html
      -> typescriptsources
                          -> main.ts
                          -> person.ts

ts文件的来源如下:

 // main.ts
 import {Person} from './person';
 var person : Person = new Person("Sergey" , "Sckoriy");
 console.log(person.greet());


// person.ts
export class Person {
    name : string;
    surname : string;
    constructor (name : string , surname : string){
        this.name = name;
        this.surname = surname;
    }
    greet():string {
        var text:string = "Hello" + this.name;
        return text;
    }
}

//main.html
<html>...
    <script type = "text/javascript" src = "typescriptsources/main.js">
    <script type = "text/javascript" src = "typescriptsources/person.js"> 

现在,正在使用

进行编译
tsc --module commonjs main.js

编译结果为:

// main.js
"use strict";
exports.__esModule = true;
var person_1 = require("./person");
var person = new person_1.Person("Sergey", "Sckoriy");
console.log(person.greet());   

// person.js

"use strict";
exports.__esModule = true;
var Person = /** @class */ (function () {
function Person(name, surname) {
    this.name = name;
    this.surname = surname;
}
Person.prototype.greet = function () {
    var text = "Hello" + this.name;
    return text;
};
return Person;
}());
exports.Person = Person;

0 个答案:

没有答案
相关问题