nagy.zsolt.hun
nagy.zsolt.hun

Reputation: 6694

typescript - simple module example fails

Person.ts:

export class Person {
  private _name: string;
  constructor(name: string) {
    this._name = name;
  }
  get name(): string {return this._name};
}

test.ts:

import {Person} from "./Person";

var user = new Person("John");
document.getElementById("h1").innerHTML = user.name;

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5"
    ,"outDir" : "build"
  }
}

When opening the result in Chrome, the following error is shown on the console:

Uncaught ReferenceError: exports is not defined
at test.js:2

Upvotes: 0

Views: 492

Answers (3)

Digvijay
Digvijay

Reputation: 784

The transpiled code is below:

define(["require", "exports"], function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var Person = (function () {
        function Person(name) {
            this._name = name;
        }
        Object.defineProperty(Person.prototype, "name", {
            get: function () { return this._name; },
            enumerable: true,
            configurable: true
        });
        ;
        return Person;
    }());
    exports.Person = Person;
});

however if you see that this expects browsers to understand the module system and in this case requirejs. If you wish you can just take the snippet and use it - its perfectly fine ES5 code.

var Person = (function() {
  function Person(name) {
    this._name = name;
  }
  Object.defineProperty(Person.prototype, "name", {
    get: function() {
      return this._name;
    },
    enumerable: true,
    configurable: true
  });;
  return Person;
}());

Upvotes: 0

nagy.zsolt.hun
nagy.zsolt.hun

Reputation: 6694

My solution is based on this answer: https://stackoverflow.com/a/36769278/1977315

  1. install requireJs

    npm install requirejs
    
  2. include requireJs in the html page

    <h1 id="h1"></h1>
    <script src="../node_modules/requirejs/require.js" data-main="test.js"></script>
    
  3. compile the code with the module amd arg:

    tsc -module amd
    

Upvotes: 1

radix
radix

Reputation: 760

You need to make your app compatible with browsers. for example using webpack:

> npm install webpack -g
> webpack build/test.js bundle.js

and in your html

<script src="/bundle.js"></script>

Typescript compilation will compile your files with commonjs module resolution, Which will not work in browsers (nodejs uses commonjs). Webpack is an example for a bundler that will take you app and make it browser ready.

Upvotes: 0

Related Questions