TypeScript replace with import

2019-07-27 05:03发布

I'm trying to write some TypeScript application and came up to conclusion that i don't like <reference path /> statement. I find it more suitable to use import 'something' instead.

But when I try to replace my reference paths i keep getting an error that module is unknown.

Here's my folder structure:

/app
    /ViewModels
        ApplicationViewModel.ts
    app.ts

ApplicationViewModel.ts

module ApplicationVM {
    export class ApplicationViewModel {
        constructor(public test:string) {
        }
    }
}

app.ts

/// <reference path="ViewModels/ApplicationViewModel.ts" />

var a = new ApplicationVM.ApplicationViewModel('test');

this one works just fine. How do i get following code to work as well?

import * as App from 'noidea';
var a = new App.ApplicationViewModel('test');

For 'noidea' i tryed: 'ViewModels/ApplicationViewModel', 'ApplicationVM' asl. I even combined it with <reference path /> but it didn't help as well.

2条回答
叼着烟拽天下
2楼-- · 2019-07-27 05:09

You need to use so called external modules:

ApplicationViewModel.ts

module ApplicationVM {
    export class ApplicationViewModel {
        constructor(public test:string) {
        }
    }
}

export = ApplicationVM;

app.ts

import { ApplicationViewModel } from "./ViewModels/ApplicationViewModel"
var a = new ApplicationViewModel('test');
查看更多
Root(大扎)
3楼-- · 2019-07-27 05:20

Remove module declaration from ApplicationViewModel.ts (each file is already a module if you use external modules):

export class ApplicationViewModel {
    constructor(public test:string) {
    }
}

Then in your app.ts

import * as App from './ViewModels/ApplicationViewModel';
var a = new App.ApplicationViewModel('test');
查看更多
登录 后发表回答