您需要在package.json
.
main
-- 告诉模块加载器模块的入口点是什么,而不是index.js
.
typings
-- 为模块设置 TypeScript 定义文件。
例如,假设我们有一个@company/foo
包含以下字段的模块package.json
,
{
"main": "lib/bundle.js",
"typings": "index.d.ts"
}
现在在你的tsconfig.json
,你想要moduleResolution
设置:
{
"moduleResolution": "node"
}
当您从 导入时@company/foo
,
import { bar } from '@company/foo';
在您的index.d.ts
中,您应该有这一行来声明 bar:
declare function bar();
TypeScript 将尝试bar
从node_modules/@company/foo/index.d.ts
.
更新:
这是从不同模块重新导出单个函数/对象并导出命名空间的完整示例。这个文件应该被调用index.d.ts
或main.d.ts
等等,所以它被 TypeScript 识别为环境定义。
import * as another from './src/another';
declare namespace hello {
function bar();
interface ProgrammerIntf {
work();
walk();
play();
}
class Programmer implements ProgrammerIntf {
work();
walk();
play();
}
export import world = another.world;
}
export default hello;
要使用这个命名空间,在调用者脚本中,
import hello from '@company/foo';
hello.bar();
hello.world();
let programmer = new hello.Programmer();
更新 2:
我在TypeScript 的文档中找到了一种我以前没有注意到的方法。
您可以在global
范围内声明所有类型,如下所示:
import * as another from './src/another';
declare global {
namespace hello {
function bar();
interface ProgrammerIntf {
work();
walk();
play();
}
class Programmer implements ProgrammerIntf {
work();
walk();
play();
}
export import world = another.world;
}
}
然后在调用者脚本中,只需使用:
import '@company/foo';
hello.bar();
hello.world();
let programmer = new hello.Programmer();
当然,如果你在你的包的开头捆绑声明,你应该可以hello
直接使用而不需要导入语句。