Transpile typescript for use in browser

女生的网名这么多〃 提交于 2019-12-12 17:47:02

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/36769197/transpile-typescript-for-use-in-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!