0

I'm newbie use typescript. In my project have knockout ts, after compile (Intellij plugin auto compile ts -> js)

this is file sample.ts:

import * as ko from "knockout"; ko;

class HelloViewModel {
    language: KnockoutObservable<string>
    framework: KnockoutObservable<string>

    constructor(language: string, framework: string) {
        this.language = ko.observable(language);
        this.framework = ko.observable(framework);
    }
}

ko.applyBindings(new HelloViewModel("TypeScript", "Knockout"));

sample.js:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ko = require("knockout");
ko;
var HelloViewModel = /** @class */ (function () {
    function HelloViewModel(language, framework) {
        this.language = ko.observable(language);
        this.framework = ko.observable(framework);
    }
    return HelloViewModel;
}());
ko.applyBindings(new HelloViewModel("TypeScript", "Knockout"));

when run on browser it notice error: Uncaught ReferenceError: exports is not defined at sample.js:2

I try to search but still not find solution. Please show me if you have a way to solve it.

This my project: https://github.com/hoangdangduy/StreamingVideoWeb

Hoang
  • 829
  • 11
  • 18

3 Answers3

0

You are missing the define statement in your JS file. It should look more like:

define(["require", "exports", "knockout"], function (require, exports, ko) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    ko;
    var HelloViewModel = /** @class */ (function () {
        function HelloViewModel(language, framework) {
            this.language = ko.observable(language);
            this.framework = ko.observable(framework);
        }
        return HelloViewModel;
    }());
    ko.applyBindings(new HelloViewModel("TypeScript", "Knockout"));
});

This is from copy-pasting your code into the TypeScript REPL.

Also, you can change

import * as ko from "knockout"; ko;

to

import ko from "knockout";
Joe Wilson
  • 5,591
  • 2
  • 27
  • 38
  • file js was automatic compile by plugin so I don't want add define manually. And I also try to add 'define' as you say but still notice error 'define is not defined' – Hoang Mar 29 '18 at 18:52
  • Ah, I see. Then see this answer https://stackoverflow.com/questions/43472778/typescript-exports-is-not-defined – Joe Wilson Mar 29 '18 at 19:07
0

require/exports do not exist in the browser.

You will need to use a bundler in addition to TypeScript, such as webpack.

Alternatively, you can try using the "module": "umd" in your tsconfig.json

caseyWebb
  • 1,997
  • 17
  • 18
0

Thanks all, I solved it, I use add requirejs to load module after my file ts and knokout ts was compiled.

Hoang
  • 829
  • 11
  • 18