我已经和Typescipt一起工作了几个月,这方面已经在几个项目的过程中让我烦恼了.假设我有以下项目结构:
project
+- app
| +- component1
| | +- component1.ts
| +- component2
| | +- component2.ts
| +- utils
| +- utils.ts
+- tsconfig.json
Run Code Online (Sandbox Code Playgroud)
现在,假设utils.ts文件包含许多辅助类(例如数据结构)甚至可能包含全局函数,并且项目中的几乎每个其他文件至少使用其中的一部分.如何使用最少量的样板代码?
使用import语句
// utils.ts
export function foo() { return 1; }
// component1.ts
import { foo, bar, baz, ...(a long list here) } from '../utils/utils'
let x = foo(); // looks fine
Run Code Online (Sandbox Code Playgroud)
优点:进口会员使用简单
缺点:几乎每个其他文件都需要维护长导入列表
另一个选择是一次导入所有内容:
// component1.ts
import * as utils from '../utils/utils' // I have to remember to put this line on top …Run Code Online (Sandbox Code Playgroud) typescript ×1