转译在浏览器中使用的打字稿

Eld*_*mir 7 javascript browserify typescript

我正在尝试在 Typescript 中编写我的前端代码并希望导出代码,我的浏览器可以在 <script src="..."></script>.

我是通过 browserify 和 tsify 这样做的。我的问题是我的代码不能在全局命名空间中访问。将脚本加载到<script>标签中会执行它,当然,但是如果我打算像可以在 inline <script>s 或类似中使用的函数库一样加载它怎么办?

更新

一个例子是

索引.ts

function foo(): void {
    console.log("bar");
}
Run Code Online (Sandbox Code Playgroud)

使用以下 conf 编译会产生以下 javascript

配置文件

{
    "compilerOptions": {
        "module": "UMD",
        "target": "es5",
        "noImplicitAny": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "sourceMap": true
    }
}
Run Code Online (Sandbox Code Playgroud)

索引.js

function foo() {
    console.log("bar");
}
Run Code Online (Sandbox Code Playgroud)

这可以。但是,如果 index.js 导入了一些东西,例如我的notification函数,那么我会得到这个

(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");
    }
});
Run Code Online (Sandbox Code Playgroud)

现在foo被包裹在某个范围内,当我在我的网站上加载它时不可用:<script src="require.js" data-main="index"></script>

foo is undefined
Run Code Online (Sandbox Code Playgroud)

Fen*_*ton 4

在模块加载作为本机 JavaScript 功能出现在浏览器中之前,您可以使用 RequireJS 或 SystemJS 等库来加载模块。

使用 RequireJS 时,您只需传递编译器选项:

-module UMD
Run Code Online (Sandbox Code Playgroud)

然后将 RequireJS 指向您的主文件:

<script src="require.js" data-main="app"></script>
Run Code Online (Sandbox Code Playgroud)

然后根据需要异步加载模块,生活就很好了。

  • 模块加载是否符合要求?如果我的主文件导入/需要一些文件,而不是在转译代码中保留“require”语句,则不能将所需的文件连接起来 (2认同)