在 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
.
// 👇️ named export export const department = 'web dev'; // 👇️ named export export const tasks = ['develop', 'design', 'test'];
export
在与变量定义相同的行上使用与在声明变量后将其导出为对象相同。
const department = 'web dev'; const tasks = ['develop', 'design', 'test']; // 👇️ named exports (same as code snippet above) export {department, tasks};
以下是我们如何将变量导入名为index.js
.
import {department, tasks} from './another-file.js'; console.log(department); // 👉️ 'web dev' console.log(tasks); // 👉️ ['develop', 'design', 'test']
如果必须,请确保更正指向another-file.js
模块的路径。该示例假定another-file.js
和index.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.
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.
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.
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.
// 👇️ 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.
每个文件只能有一个默认导出,但您可以根据需要拥有任意多个命名导出。
您也不必考虑使用默认导出或命名导出导出哪些成员。