JavaScript 中的 export
关键字用于将函数、对象或原始值导出为模块的一部分,以便其他模块可以通过 import
语句使用它们。这是 ES6 模块系统的一部分,它提供了一种定义和使用模块的标准方法。
export default
关键字导出一个值。export
关键字后跟变量、函数或类的声明。// mathFunctions.js
const add = (x, y) => x + y;
const subtract = (x, y) => x - y;
export default {
add,
subtract
};
然后在另一个文件中导入:
// app.js
import mathFunctions from './mathFunctions.js';
console.log(mathFunctions.add(1, 2)); // 输出: 3
// mathFunctions.js
export const add = (x, y) => x + y;
export const subtract = (x, y) => x - y;
然后在另一个文件中导入:
// app.js
import { add, subtract } from './mathFunctions.js';
console.log(add(1, 2)); // 输出: 3
console.log(subtract(3, 1)); // 输出: 2
原因:可能是路径错误、文件扩展名未指定或模块系统不兼容。
解决方法:
.mjs
文件或设置了 "type": "module"
在 package.json
中,则需要包含文件扩展名。原因:可能是因为不清楚如何同时使用命名导出和默认导出。
解决方法:
{}
来导入命名导出,不要加 default
关键字。// 导出
export const namedExport = 'named';
export default 'default';
// 导入
import defaultExport, { namedExport } from './module.js';
console.log(defaultExport); // 输出: 'default'
console.log(namedExport); // 输出: 'named'
通过这种方式,可以清晰地区分和使用默认导出与命名导出。
领取专属 10元无门槛券
手把手带您无忧上云