从 TypeScript 中的另一个文件重新导出值

在 TypeScript 中从另一个文件重新导出值

Re-export values from another file in TypeScript

要从 TypeScript 中的另一个文件重新导出值,请确保导出名称 exports asexport {myFunction, myConstant} from './another-file和默认 export as export {default} from './another-file'

这些值可以从重新导出它们的文件中导入。

下面是一个文件示例,该文件具有 2 个命名导出和一个默认导出。

另一个文件.ts
// 👇️ named export export function getEmployee() { return { id: 1, salary: 100 }; } // 👇️ named export export const greeting = 'hello world'; // 👇️ default export export default function sum(a: number, b: number) { return a + b; }

以下是如何another-file.ts从名为index.ts.

索引.ts
export { getEmployee, greeting, default } from './another-file';

上面的示例直接重新导出了 2 个命名导出和默认导出。

这意味着你不能使用getEmployee,greeting 和文件中的默认导出index.ts,因为我们没有导入它们,我们直接重新导出它们。

如果必须使用文件中的值,则还必须导入它们。

索引.ts
// 👇️ import (only if you need to use them in index.ts) import sum, { getEmployee, greeting } from './another-file'; // 👇️ re-export export { getEmployee, greeting, default } from './another-file'; console.log(sum(10, 15)); console.log(getEmployee()); console.log(greeting);

重新导出另一个模块的成员的语法是:

索引.ts
// 👇️ re-export NAMED exports export { getEmployee, greeting } from './another-file'; // 👇️ re-export DEFAULT export export { default } from './another-file';

如果您要重新导出同一文件的成员,则可以将上例中的两行合并为一行。

如果您要从多个文件中重新导出成员,则必须为每个文件使用一行代码。
索引.ts
// 👇️ re-export NAMED exports export { getEmployee, greeting } from './first-file'; // 👇️ re-export default export export { default } from './second-file';

然后您可以从同一模块导入重新导出的成员。

第三个文件.ts
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:

index.ts
import sum, { getEmployee, greeting } from './'; // 👈️ implicit 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.