如何在 JavaScript 中导出变量

在 JavaScript 中导出变量

How to export Variables in JavaScript

使用命名导出在 JavaScript 中导出多个变量,例如
export const A = 'a'export const B = 'b'. 可以使用命名的 import as 导入导出的变量import {A, B} from './another-file.js'您可以在一个文件中根据需要拥有尽可能多的命名导出。

下面是从名为another-file.js.

另一个文件.js
// 👇️ named export export const department = 'web dev'; // 👇️ named export export const tasks = ['develop', 'design', 'test'];

export在与变量定义相同的行上使用与在声明变量后将其导出为对象相同。

另一个文件.js
const department = 'web dev'; const tasks = ['develop', 'design', 'test']; // 👇️ named exports (same as code snippet above) export {department, tasks};

以下是我们如何将变量导入名为index.js.

索引.js
import {department, tasks} from './another-file.js'; console.log(department); // 👉️ 'web dev' console.log(tasks); // 👉️ ['develop', 'design', 'test']

如果必须,请确保更正指向another-file.js模块的路径。该示例假定another-file.jsindex.js位于同一目录中。

例如,如果您从一个目录向上导入,您会做
import {department, tasks} from '../another-file.js'.

导入变量时,我们将变量的名称用花括号括起来。这称为命名导入。


导入/导出语法在 JavaScript
中称为
ES6 模块。

为了能够从不同的文件导入变量,必须使用命名导出或默认导出来导出它。

上面的示例使用命名导出和命名导入。

命名和默认导出和导入之间的主要区别是 – 每个文件可以有多个命名导出,但只能有一个默认导出。

If you try to use multiple default exports in a single file, you would get an
error.

another-file.js
const department = 'web dev'; const tasks = ['develop', 'design', 'test']; export default department; // ⛔️ Error. Not allowed to have 2 default exports in a file export default tasks;

IMPORTANT: If you are exporting a variable (or an arrow function) as a
default export, you have to declare it on 1 line and export it on the next. You
can’t declare and default export a variable on the same line.

Having said that, you can use 1 default export and as many named exports as you need in a single file.

Let’s look at an example that exports multiple variables and uses both – default
and named exports.

another-file.js
const department = 'web dev'; // 👇️ default export export default department; // 👇️ named export export const tasks = ['develop', 'design', 'test'];

And here is how you would import the two variables.

index.js
// 👇️ default and named imports import department, {tasks} from './another-file.js'; console.log(department); // 👉️ 'web dev' console.log(tasks); // 👉️ ['develop', 'design', 'test']

Notice that we didn’t wrap the default import in curly braces.

We used a default import to import the department variable and a named import
to import the tasks variable.

每个文件只能有一个默认导出,但您可以根据需要拥有任意多个命名导出。

根据我的经验,大多数真实世界的代码库都专门使用命名导出和导入,因为它们可以更轻松地利用 IDE 进行自动完成和自动导入。

您也不必考虑使用默认导出或命名导出导出哪些成员。

发表评论