在JavaScript中,export
关键字用于从模块中导出函数、对象或原始值,以便其他模块可以通过import
语句使用它们。这是ES6模块系统的一部分,旨在提供一种标准化的方式来组织和共享代码。
// mathFunctions.js
const add = (x, y) => x + y;
const subtract = (x, y) => x - y;
export default {
add,
subtract
};
// utils.js
export const greet = (name) => `Hello, ${name}!`;
export const farewell = (name) => `Goodbye, ${name}!`;
// app.js
import math from './mathFunctions.js';
import { greet, farewell } from './utils.js';
console.log(math.add(1, 2)); // 输出: 3
console.log(math.subtract(3, 1)); // 输出: 2
console.log(greet('Alice')); // 输出: Hello, Alice!
console.log(farewell('Bob')); // 输出: Goodbye, Bob!
原因:
解决方法:
.js
)。export
关键字。// 错误的导入方式
import math from './mathFunctions'; // 缺少文件扩展名
// 正确的导入方式
import math from './mathFunctions.js';
通过这种方式,可以确保模块化代码的正确性和可维护性。
领取专属 10元无门槛券
手把手带您无忧上云