如何在JavaScript中导出函数以便在外部模块和其他脚本中使用?
在JavaScript中,可以使用export
关键字将函数导出以便在其他模块或脚本中使用。以下是几种方法:
方法一:使用命名导出
在函数声明前使用export
关键字并指定函数名称,如下所示:
// module.js
export function add(a, b) {
return a + b;
}
// script.js
import { add } from './module.js';
console.log(add(2, 3)); // Output: 5
在上面的示例中,我们将add
函数导出并在另一个脚本中使用它。
方法二:使用默认导出
可以使用export default
关键字将函数作为默认导出,如下所示:
// module.js
export default function add(a, b) {
return a + b;
}
// script.js
import add from './module.js';
console.log(add(2, 3)); // Output: 5
在上面的示例中,我们将add
函数作为默认导出,并在另一个脚本中使用它。
方法三:导出多个函数
可以使用命名导出和默认导出组合来导出多个函数,如下所示:
// module.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
export default function multiply(a, b) {
return a * b;
}
// script.js
import multiply, { add, subtract } from './module.js';
console.log(add(2, 3)); // Output: 5
console.log(subtract(5, 2)); // Output: 3
console.log(multiply(2, 3)); // Output: 6
在上面的示例中,我们将add
和subtract
函数作为命名导出,将multiply
函数作为默认导出,并在另一个脚本中使用它们。
这些是在JavaScript中导出函数的几种方法。