require - 如果我使用 `module("somelib")` in typescript, it can' t 在浏览器中运行

标签 require typescript commonjs

我正在尝试在客户端使用 typescript 和 angularjs。

我发现如果我使用外部模块,生成的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) {});
        }
    }
}

生成的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 = {}));

无法正常运行。但是,如果我删除 module("underscore") 部分,就可以了。

由于我在HTML中添加了underscore.js,我想应该是require()方法出了问题。如何解决?

最佳答案

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

捆绑

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

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

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

module test {
    export class Ctrl {

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

模块加载

如果你想使用模块加载器,对于 Web 通常是 RequireJS,你可以使用 import 语句加载外部模块。通常在这种情况下您不需要引用...

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

module test {
    export class Ctrl {

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

RequireJS 与非模块

还有第三种情况,这很常见。如果你打算import something that isn't an External Module (例如 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({});
});

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

  require.config({
    paths: {
        "underscore": "libs/underscore"
    }
  });

关于require - 如果我使用 `module("somelib")` in typescript, it can' t 在浏览器中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14538099/

相关文章:

javascript - 在 Webpack 中导入使用 npm 安装的 "regular"javascript 包

node.js - "Error: Cannot find module ' 少 '"Node.js 模块加载首选项/顺序/缓存?

typescript - 从 typescript 中的非静态函数访问静态成员

javascript - 如何将任何类型对象分配\转换\转换为特定类型?

javascript - 使用导入/导出默认语法从存储库导入文件时 Jest 失败

node.js - 在 Node.JS 中是否有 require() 的替代方法? "soft require"尝试查找文件但如果不存在则不会出错

Lua 需要 block 环境

javascript - 不能在 Electron 中要求来自渲染器的自定义模块

generics - TypeScript:当前类的类型作为类型变量

node.js - TypeScript 不会解析外部模块 (node.js)