如果我在typescript中使用`module("somelib")`,它就无法在浏览器中运行

Fre*_*ind 4 require commonjs typescript

我正在尝试在客户端使用带有angularjs的typescript.

我发现如果使用外部模块,生成的js将不会在浏览器中运行.

controllers.ts

/// <reference path="./libs/underscore.d.ts"/>

import _ = module("underscore");

module test {
    export class Ctrl {

        constructor($scope:any) {
            $scope.name = "Freewind";
            _.each($scope.name, function(item) {});
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

生成的js将是:

var _ = require("underscore")
var test;
(function (test) {
    var Ctrl = (function () {
        function Ctrl($scope) {
            $scope.name = "Freewind";
            _.each($scope.name, function (item) {
            });
        }
        return Ctrl;
    })();
    test.Ctrl = Ctrl;    
})(test || (test = {}));
Run Code Online (Sandbox Code Playgroud)

哪个无法正常运行.但如果我删除该module("underscore")部分,它就可以了.

由于我在HTML中添加了underscore.js,我认为该require()方法应该是错误的.怎么解决?

Fen*_*ton 5

有两种方法可以在HTML页面中加载内容.

捆绑

第一个是手动包含页面中的所有脚本文件.您可能会运行某种预发布步骤来合并和缩小代码 - 但是您要对此负责,而不是将其留给代码来执行.这通常称为捆绑.

在捆绑的情况下,您只在TypeScript代码中使用引用(而不是导入),如下所示:

/// <reference path="./libs/underscore.d.ts"/>

module test {
    export class Ctrl {

        constructor($scope:any) {
            $scope.name = "Freewind";
            _.each($scope.name, function(item) {});
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

模块加载

如果要使用模块加载器(对于Web通常为RequireJS),可以使用import语句加载外部模块.通常在这种情况下你不需要参考......

import _ = module("./libs/underscore");

module test {
    export class Ctrl {

        constructor($scope:any) {
            $scope.name = "Freewind";
            _.each($scope.name, function(item) {});
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

RequireJS与非模块

第三种情况很常见.如果您打算导入不是外部模块的东西(例如jQuery,但下划线也可能适合此模式),那么最好使用RequireJS的引用和手动调用.

RequireJS将为您加载依赖项,因此您将使用它包装主程序(这可能是在一个单独的文件中,如app.ts.

///<reference path="./libs/require.d.ts" />
///<reference path="./libs/underscore.d.ts" />

module test {
    export class Ctrl {

        constructor($scope:any) {
            $scope.name = "Freewind";
            _.each($scope.name, function(item) {});
        }
    }
}

require(['underscore'], function (_) {
    var ctrl = new test.Crtl({});
});
Run Code Online (Sandbox Code Playgroud)

您还可以使用require.config在应用程序中指定下划线的路径.

  require.config({
    paths: {
        "underscore": "libs/underscore"
    }
  });
Run Code Online (Sandbox Code Playgroud)