TypeScript replace with import

2019-07-27 05:27发布

问题:

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.

回答1:

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');


回答2:

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');