export 与 import 模块导入导出各种类型的变量,如字符串,数值,函数,类。
- 导出的函数声明与类声明必须要有名称(export default 命令另外考虑)。
- 不仅能导出声明还能导出引用(例如函数)。
- export 命令可以出现在模块的任何位置,但必需处于模块顶层。
- import 命令会提升到整个模块的头部,首先执行。
- /**
- * index.js
- * @author 恪晨
- * @since 2023/8/17
- */
- // 方式1
- // const hello = function(key){
- // console.log('Hello World!');
- // };
- // exports.hello = hello;
- //
- // 方式2
- class WangTest {
- static print() {
- console.log(11);
- }
- }
- export default WangTest;
- // 方式3
- // const test1 = function () {
- // return 'test1';
- // }
- //
- // const test2 = function () {
- // console.log('test2');
- // }
- //
- // module.exports = {
- // test1,
- // test2
- // }
复制代码- /*-----export [test.js]-----*/
- let myName = "Tom";
- let myAge = 20;
- let myfn = function(){
- return "My name is" + myName + "! I'm '" + myAge + "years old."
- }
- let myClass = class myClass {
- static a = "yeah!";
- }
- export { myName, myAge, myfn, myClass }
-
- /*-----import [xxx.js]-----*/
- import { myName, myAge, myfn, myClass } from "./test.js";
- console.log(myfn());// My name is Tom! I'm 20 years old.
- console.log(myAge);// 20
- console.log(myName);// Tom
- console.log(myClass.a );// yeah!
复制代码
|