如何在不使依赖代码成为模块的情况下导入 TypeScript AMD 模块

How can I import TypeScript AMD modules without making the dependent code a module

我有一个 Chrome 扩展内容脚本,它有 2 个 AMD 依赖项。当我使用 requirejs "require" 函数加载依赖项时,脚本工作正常。

我将脚本与项目的其余部分一起移植到 TypeScript,现在正在使用

导入依赖=要求("Dependency");

一切都很好,这些模块已经移植到 TS 并且在项目的其他部分工作正常。

我的问题是,一旦我添加了一个 import 语句,TS 编译器就想把我的脚本变成一个模块,并且在生成的 JS 中它使用 requirejs "define" 导入模块。我的 chrome 分机对此不太满意,当我 运行 它时,我收到 "mismatched anonymous define" 错误。

有没有办法让打字稿编译器使用 require 函数来加载我的模块,而不是让我的脚本成为一个模块?我很难找到与此相关的任何信息。

处理这个问题的最佳方法是实际使用 commonjs 标志进行编译,并利用 TypeScript 编译器实际上不会发出 require 语句的事实,如果不使用模块导入处于价值地位。这类似于 Modules in TypeScript 页面中记录的 "optional module loading" 高级方案。

示例代码:

declare var require: any; // If needed
import _a = require('Dependency');
import _b = require('SomeOtherDependency');

var a: typeof _a = require('Dependency');
var b: typeof _b = require('SomeOtherDependency');

// Use 'a' and 'b' in your code. Do not use _a or _b.
a.doSomething();