JavaScript 程序:将一个JS文件包含到另一个JS文件中

要理解此示例,您应了解以下 JavaScript 编程 主题


示例:使用 import/export

让我们创建一个名为 module.js 的文件(文件名可以是任何名称),其中包含以下内容

// program to include JS file into another JS file

const message = 'hello world';

const number = 10;

function multiplyNumbers(a, b) {
    return a * b;
}

// exporting variables and function
export { message, number, multiplyNumbers };

为了将这些变量和函数包含在另一个文件(例如 main.js)中,您可以使用 import 关键字,如下所示:

// import the variables and function from module.js
import { message, number, multiplyNumbers } from './modules.js';

console.log(message); // hello world

console.log(number); // 10

console.log(multiplyNumbers(3, 4)); // 12
console.log(multiplyNumbers(5, 8)); // 40

要包含另一个文件,您必须使用 export 语句导出要在另一个文件中使用的代码。例如:

export { message, number, multiplyNumbers };

您也可以进行单独导出。例如:

export const message = 'hello world';

export const number = 10;

要包含另一个文件中的代码,您必须使用 import 语句并通过文件路径进行导入。例如:

// importing codes from module file
import { message, number, multiplyNumbers } from './modules.js';

然后,您可以像使用同一文件中的代码一样使用它们。

这有助于编写更清晰、更易于维护和更模块化的代码。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战