ES6(javascript)模块化之导入导出方式详解

export导出,import导入

导出、导入变量、函数、类:
方式一:

//main.js
//导出
   export let name='zxc'
   export function test() {
      console.log('haha')
  }
  export class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age
    }
}
  //app.js
  //导入
 //import命令接受一对大括号,
 //里面指定要从其他模块导入的变量名。大括号里面的变量名,
 //必须与被导入模块(main.js)对外接口的名称相同。
  import { name,test,Person } from './main.js'
  

方式二:

  //main.js
  //导出
   let name='zxc'
   export { name }
   
   function test() {
    console.log('haha')
   }
   export { test }
   
   class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age
    }
}
export { Person }
   //如果在同一个js文件中可以一起导出
    export { name,test,Person }
    
      //app.js
      //导入
      import { name,test,Person } from './main.js'

      

方式三:

    //在导出时还可以起别名
    //main.js
    //导出
    let name='zxc'
   
    function test() {
     console.log('haha')
    }
    class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age
    }
  }
    
    //as后是别名
    export {name as n,test as t,Person as p}
   
    
    //app.js
    //导入
    import { n,t,p } from './main.js'
    //导入时也可起别名
    import {n as na,t as te,p as pe } from './main,js'
    

export default 默认导出:

//其他模块导入该模块时,import命令可以为该匿名函数指定任意名字。
//main.js
//导出
export default function() {
  console.log('hia');
}

//export default也可用在非匿名函数前,别的模块导入该模块时,
//函数名无效,还是如同匿名函数一样
export default function test() {
  console.log('hia');
}

 //app.js
 //导入
 //默认导出的,其他模块导入该模块时,
 //import命令可以为该匿名函数指定任意名字。
 //使用export default时,对应的import语句不需要使用大括号
import tt from './main.js'


// 以下代码等同于
// export default add;
function add(a, b) {
  return a+b;
}
export {add as default};


// 以下代码等同于
// import bar from 'swiper';
import { default as bar } from 'swiper';

//注意:export default 一个模块中只能用一次

模块的整体加载:
在导入模块时,可用 * 指定一个对象表示整个要导入的模块

//main.js
export function add(a,b) {
  return a+b;
}

export let a='cbx'
export class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age
    }
}
//app.js
import * as main from './main.js'

console.log(main.add(2,3));
console.log(main.a);
let tom =new main.Person('tom',18)
console.log(tom.name)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

H落花流水

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值