[英]TypeScript - export library with 'namespaces'
Ok, so for example I have a project with following file structure: 好的,例如,我有一个具有以下文件结构的项目:
Let the project be called 'my-module' 让项目称为“我的模块”
I'd like import this library to other project like that: 我想像这样将这个库导入其他项目:
import { User, Home } from 'my-module/Models'
import { BaseWindow } from 'my-module/View'
How I can do that? 我该怎么做? How to prepare .d.ts file?
如何准备.d.ts文件?
EDIT: 编辑:
Content of the above files are simple for example: 上述文件的内容很简单,例如:
interface IUser {
name: string;
age: number;
}
type UserOptions = IUser & {
foo: string
}
class User implements IUser {
private foo: string;
name: string;
age: number;
constructor(options: UserOptions) {
this.name = options.name;
this.age = options.age;
this.foo = options.foo;
}
}
export { User, UserOptions };
I'm guessing what you want in src/Models/index.ts
is: 我猜你想在
src/Models/index.ts
是什么:
export * from "./User";
export * from "./Home";
Then, assuming you have module resolution set up appropriately, you can write: 然后,假设您已经适当设置了模块分辨率,则可以编写:
import { User, UserOptions } from "my-module/Models";
and User
and UserOptions
will refer to the class and the type alias from src/Models/User.ts
, respectively. 和
User
和UserOptions
将分别从src/Models/User.ts
引用类和类型别名。 If src/Models/User.ts
and src/Models/Home.ts
declare a symbol with the same name, I believe the first export *
statement wins. 如果
src/Models/User.ts
和src/Models/Home.ts
声明具有相同名称的符号,则我相信第一个export *
语句会获胜。
If an import of my-module/
is giving you completions of src
and dist
, then you would need to import the full relative path to the .js
and .d.ts
files (which should be next to each other). 如果
my-module/
的导入使您可以完成src
和dist
,则需要将完整的相对路径导入到.js
和.d.ts
文件(应该彼此相邻)。 I assume these files are under dist
. 我认为这些文件在
dist
下。 If you don't like the dist
in your import path, you have a few options, none of them great: 如果您不喜欢导入路径中的
dist
,则可以选择几种方法,但都不是很好的选择:
src
and dist
directories; src
和dist
目录; arrange all files starting from the root of the project. import "my-module/Models"
looks in the dist
folder. import "my-module/Models"
在dist
文件夹中。 If your bundler or loader doesn't already integrate with TypeScript, use TypeScript's path mapping options to make TypeScript's module resolution behavior mirror that of your bundler or loader. dist
by manually creating either a pair of .js
and .d.ts
files that import the real paths or a package.json
file with main
and types
fields that refer to the real paths. .js
和.d.ts
文件或一个具有引用真实路径的main
和types
字段的package.json
文件,分别将每个导入路径重定向到dist
下的适当文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.