如何在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

在上面的示例中,我们将addsubtract函数作为命名导出,将multiply函数作为默认导出,并在另一个脚本中使用它们。

这些是在JavaScript中导出函数的几种方法。



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.