如何让 TypeScript 理解像 "plugin!./path/to/foo" 这样的 RequireJS 插件的导入路径?
How to make TypeScript understand import paths for RequireJS plugins like "plugin!./path/to/foo"?
例如,假设我们写
import template from 'hb!./foo.hb'
我们如何让 TypeScript 理解它(或者忽略它,因为 RequireJS 会处理它)?
添加环境模块声明将使 TypeScript 了解该模块,并防止编译器错误。
来自关于 module resolution 的 TypeScript 文档:
The compiler will try to locate a file that represents the imported module. To do so the compiler follows one of two different strategies: Classic or Node.
If that didn’t work and if the module name is non-relative, then the compiler will attempt to locate an ambient module declaration.
在您的情况下,您可以添加环境模块定义:
//foo.d.ts
declare module "hb!./foo.hb" {
export default class template { }
}
然后你可以这样编译:
tsc --module amd .\test.ts .\foo.d.ts
并得到这个输出:
define(["require", "exports", "hb!./foo.hb"], function (require, exports, foo_hb_1) {
"use strict";
console.log(foo_hb_1["default"]);
});
这里重要的是环境模块声明只是告诉 TypeScript template
会是什么样的东西。正如您从编译输出中看到的那样,您的模块加载器实际上将负责实际工作。
更新
可以在模块声明中使用 wildcards。所以你可以像这样声明一个模块:
declare module "hb!*" {
export default class template { }
}
现在您可以导入任何符合 hb!*
:
的内容
import template from 'hb!./foo.hb'
import template from 'hb!./bar.hb'
import template from 'hb!./baz.hb'
例如,假设我们写
import template from 'hb!./foo.hb'
我们如何让 TypeScript 理解它(或者忽略它,因为 RequireJS 会处理它)?
添加环境模块声明将使 TypeScript 了解该模块,并防止编译器错误。
来自关于 module resolution 的 TypeScript 文档:
The compiler will try to locate a file that represents the imported module. To do so the compiler follows one of two different strategies: Classic or Node.
If that didn’t work and if the module name is non-relative, then the compiler will attempt to locate an ambient module declaration.
在您的情况下,您可以添加环境模块定义:
//foo.d.ts
declare module "hb!./foo.hb" {
export default class template { }
}
然后你可以这样编译:
tsc --module amd .\test.ts .\foo.d.ts
并得到这个输出:
define(["require", "exports", "hb!./foo.hb"], function (require, exports, foo_hb_1) {
"use strict";
console.log(foo_hb_1["default"]);
});
这里重要的是环境模块声明只是告诉 TypeScript template
会是什么样的东西。正如您从编译输出中看到的那样,您的模块加载器实际上将负责实际工作。
更新
可以在模块声明中使用 wildcards。所以你可以像这样声明一个模块:
declare module "hb!*" {
export default class template { }
}
现在您可以导入任何符合 hb!*
:
import template from 'hb!./foo.hb'
import template from 'hb!./bar.hb'
import template from 'hb!./baz.hb'