Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transpile typescript for use in browser

I am trying to write my frontend code in Typescript and want to export the code, that my browser can load in <script src="..."></script>.

I did so by way of browserify and tsify. My trouble is that not on my code is accessible in the global namespace. Loading the script in a <script> tag will execute it, sure, but what if I intend it to be loaded like a library of functions that can be used in inline <script>s or similar?

Update

An example would be

index.ts

function foo(): void {
    console.log("bar");
}

Compiling with the following conf produces the following javascript

tsconfig.json

{
    "compilerOptions": {
        "module": "UMD",
        "target": "es5",
        "noImplicitAny": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "sourceMap": true
    }
}

index.js

function foo() {
    console.log("bar");
}

This is fine. However, if index.js imports something, e.g. my notification function, then I get this

(function (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(["require", "exports", "./notifications"], factory);
    }
})(function (require, exports) {
    "use strict";
    var notifications_1 = require("./notifications");
    notifications_1.notification("blerp");
    function foo() {
        console.log("bar");
    }
});

Now foo is wrapped in some scope, and is not available when I load it on my website: <script src="require.js" data-main="index"></script>

foo is undefined
like image 439
Eldamir Avatar asked Apr 21 '16 12:04

Eldamir


1 Answers

Until module loading lands in browsers as a native JavaScript feature, you can use a library such as RequireJS or SystemJS to load modules.

When using RequireJS, you simply pass the compiler option:

-module UMD

And then point RequireJS at your main file:

<script src="require.js" data-main="app"></script>

Modules are then loaded asynchronously on demand and life is good.

like image 142
Fenton Avatar answered Oct 02 '22 08:10

Fenton