如何导入TypeScript AMD模块而无需将相关代码作为模块 [英] How can I import TypeScript AMD modules without making the dependent code a module

查看:628
本文介绍了如何导入TypeScript AMD模块而无需将相关代码作为模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Chrome扩展内容脚本,有2个AMD依赖项。当我使用requirejsrequire函数加载依赖关系时,该脚本正常工作。



我将脚本移植到TypeScript中,并使用我的项目的其余部分, / p>

import Dependency = require(Dependency);

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

我的问题是,只要我添加一个导入语句,TS编译器就想让我的脚本到模块中,并在生成的JS中使用requirejsdefine导入模块。我的chrome扩展并不太兴奋,当我运行它时,我得到一个不匹配的匿名定义错误。



有没有办法让打印机编译器使用require函数来加载我的模块,而不是让我的脚本成为模块?

解决方案

处理这个问题的最好方法是用 commonjs 标志,并使用TypeScript编译器实际上不会发出 require 语句的事实,如果模块导入未用于价值位置。这类似于 TypeScript中的模块中记录的可选模块加载 / b>

示例代码:

  declare var require : 任何; //如果需要
import _a = require('Dependency');
import _b = require('SomeOtherDependency');

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

//在代码中使用'a'和'b'。不要使用_a或_b。
a.doSomething();


I have a Chrome extension content script that has 2 AMD dependencies. The script works fine when I load the dependencies using the requirejs "require" function.

I ported the script to TypeScript with the rest of my project, and am now using

import Dependency = require("Dependency");

which is all fine and dandy, the modules have been ported to TS and are working fine in other parts of the project.

My issue is that as soon as I add an import statement, the TS compiler wants to make my script into a module, and in the generated JS it imports the modules using requirejs "define". My chrome extension is not too thrilled about this, and when I run it I get a "mismatched anonymous define" error.

Is there any way to get the typescript compiler to use the require function to load my modules instead of making my script a module? I'm having difficulty finding anything about this.

解决方案

The best way to handle this is to actually compile with the commonjs flag and use the fact that the TypeScript compiler doesn't actually emit require statements if the module import isn't used in a value position. This is similar to the "optional module loading" advanced scenario documented in the Modules in TypeScript page.

Sample code:

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();

这篇关于如何导入TypeScript AMD模块而无需将相关代码作为模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆