vue2项目中js文件里面写了多个函数,和常量,怎么导入和导出

160 阅读1分钟

在JavaScript中,你可以使用ES6的模块系统来导出和导入函数和常量。下面是一些基本的示例:

导出:

假设你有一个名为 myModule.js 的文件,其中包含了多个函数和常量:

javascript复制代码
	// myModule.js  

	  

	// 常量  

	export const MY_CONSTANT = "Hello, World!";  

	  

	// 函数  

	export function myFunction1() {  

	  console.log("This is myFunction1");  

	}  

	  

	export function myFunction2() {  

	  console.log("This is myFunction2");  

	}

在上面的示例中,我们使用了 export 关键字来导出常量 MY_CONSTANT 和函数 myFunction1 和 myFunction2

导入:

现在,假设你想在另一个JavaScript文件中使用 myModule.js 中导出的常量和函数。你可以使用 import 关键字来导入它们:

javascript复制代码
	// anotherFile.js  

	  

	// 导入常量和函数  

	import { MY_CONSTANT, myFunction1, myFunction2 } from './myModule.js';  

	  

	// 使用导入的常量和函数  

	console.log(MY_CONSTANT); // 输出 "Hello, World!"  

	myFunction1(); // 输出 "This is myFunction1"  

	myFunction2(); // 输出 "This is myFunction2"

在上面的示例中,我们使用了 import 关键字来从 myModule.js 文件中导入常量 MY_CONSTANT 和函数 myFunction1 和 myFunction2。然后,我们就可以在 anotherFile.js 文件中使用这些导入的常量和函数了。