How to use UMD typescript module in pure javascript environment

I want typescript to translate my * .ts files to umd * .js files. The problem is that I cannot use my modules in a pure javascript environment because the modules won the t be set into thewindow` object.

tsconfig.json

{
  "compilerOptions": {
    "module": "umd",
    "removeComments": true,
    "preserveConstEnums": true,
    "sourceMap": true
  },
  "include": [
    "src/**/*.ts"
  ]
}

Src / car.js

export default class Car {
    drive() {
        console.log('Driving');
    }
}

Generated js file:

(function (dependencies, factory) {
    if (typeof module === 'object' && typeof module.exports === 'object') {
        var v = factory(require, exports); if (v !== undefined) module.exports = v;
    }
    else if (typeof define === 'function' && define.amd) {
        define(dependencies, factory);
    }
})(["require", "exports"], function (require, exports) {
    "use strict";
    var Car = (function () {
        function Car() {
        }
        Car.prototype.drive = function () {
            console.log('Driving');
        };
        return Car;
    }());
    exports.__esModule = true;
    exports["default"] = Car;
});
//# sourceMappingURL=Car.js.map

In my index.html, I want to be able to call the drive as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Title</title>

    <script src="src/Car.js"></script>
</head>
<body>

    <script>
        // On document ready
        var car = new Car();
        car.drive();
    </script>

</body>
</html>

Is this possible with typescript? Can you give an example?

EDIT: In this post, I can read that UMD typescript does not cover the standard js case: https://github.com/Microsoft/TypeScript/issues/3322 Is this correct?

+4
source share

Source: https://habr.com/ru/post/1661802/


All Articles