Tom*_*Tom 13 import export private function typescript
我希望开发人员使用类/接口而不是直接导入函数。
有没有办法限制只有类才能导入该函数?
我不想将所有功能放在一个文件中,因为它在大型项目中不可扩展
即我不想使用这种模式:
// myclass.ts
// no exports on the functions
function foo(){ ... }
function bar(){ ... }
export class MyClass {
Foo(){ return foo() }
Bar(){ return bar() }
}
Run Code Online (Sandbox Code Playgroud)
我想要实现的目标:
// foo.ts
export function foo(){ ... }
// I want this to be private but it needs to be exported so the class below can use it
// bar.ts
export function bar() { ... }
// myclass.ts
import { foo } from 'foo';
import { bar } from 'bar';
export class MyClass {
Foo(){ return foo() }
Bar(){ return bar() }
}
// anyotherfile.ts
import { foo } from 'foo' // Stop from importing directly
import { MyClass } from 'myclass' // use this instead
Run Code Online (Sandbox Code Playgroud)
使用 TypeScript 可以限制导入。
您正在谈论使用您的类的开发人员,因此我假设您将其作为 npm 包分发,这通常意味着您有一个构建步骤。
在构建步骤中,您可以将文件中的函数声明替换.d.ts
为如下内容:
export const foo: never
Run Code Online (Sandbox Code Playgroud)
这样,如果开发人员尝试使用您想要保护的函数,他们就会收到 TypeScript 错误。
当然,他们可以简单地解决// @ts-ignore
这个问题,但他们至少会知道他们没有以预期的方式使用你的库。
在构建步骤中更改文件可能不容易配置,因此作为替代方案,您可以简单地.d.ts
从“隐藏”脚本的构建中排除这些文件。
如果开发人员尝试导入它们,他们不会收到错误,但类型的缺乏应该让他们清楚地意识到他们没有使用正确的 API。
将代码拆分为多个文件并确保开发人员不会导入您不希望他们使用的函数的唯一方法是将脚本捆绑到一个文件中作为构建的一部分。
一些 npm 包已经像这样捆绑了它们的代码,作为减少包大小并缩短开发人员构建时间的一种方式。
归档时间: |
|
查看次数: |
1935 次 |
最近记录: |