Re-export values from another file in TypeScript
要从 TypeScript 中的另一个文件重新导出值,请确保导出名称 exports as
export {myFunction, myConstant} from './another-file
和默认 export as
export {default} from './another-file'
。
这些值可以从重新导出它们的文件中导入。
下面是一个文件示例,该文件具有 2 个命名导出和一个默认导出。
export function getEmployee() {
return { id: 1, salary: 100 };
export const greeting = 'hello world';
export default function sum(a: number, b: number) {
return a + b;
以下是如何another-file.ts
从名为index.ts
.
export { getEmployee, greeting, default } from './another-file';
上面的示例直接重新导出了 2 个命名导出和默认导出。
import sum, { getEmployee, greeting } from './another-file';
export { getEmployee, greeting, default } from './another-file';
console.log(sum(10, 15));
console.log(getEmployee());
console.log(greeting);
重新导出另一个模块的成员的语法是:
export { getEmployee, greeting } from './another-file';
export { default } from './another-file';
如果您要重新导出同一文件的成员,则可以将上例中的两行合并为一行。
export { getEmployee, greeting } from './first-file';
export { default } from './second-file';
然后您可以从同一模块导入重新导出的成员。
import sum, { getEmployee, greeting } from './index';
console.log(sum(100, 50));
console.log(getEmployee());
console.log(greeting);
The pattern you often see is – re-export members of different files from a file
called index.ts
. The name index.ts
is important because you don’t have to
explicitly specify the name index
when importing.
For example, assuming that third-file.ts
and index.ts
are located in the
same directory, I could import from index.ts
like so:
import sum, { getEmployee, greeting } from './';
console.log(sum(100, 50));
console.log(getEmployee());
console.log(greeting);
This is useful when you group your code in directories with descriptive names,
because you would be importing from ./utils
, rather than ./utils/index
or
./utils/nested1
, ./utils/nested2
, etc.
Many of the files you use might make use of multiple utility functions that have
been extracted into separate files, and you might not want to have 5 lines of
imports just for utility functions or constants – this is when re-exporting from
an index.ts
file comes in.