美文网首页
Module 语法——export 与 import

Module 语法——export 与 import

作者: 麦田_426 | 来源:发表于2023-10-31 13:28 被阅读0次

由于经常忘记export 和 import 的几种用法。 一直想着有机会的话,就进行一个总结,常常拿出来看看,去解决只记得一种用法,其他的都记的有些模糊的这种问题情况

首先是export

正确的用法有:

一、对外输出变量

1.1 写法一
export var firstName = 'Michael';
export var year = 1980;
1.2 写法二
var firstName = 'Michael';
var year = 1980;
export { firstName ,  year }
1.3 写法三
//抛出的时候,重命名了变量对外的接口
var firstName = 'Michael';
var year = 1980;
export { 
  firstName as first_v1 ,
  year as year_v1 
}

二、对外输出函数

对外输出函数与对外输出变量是一样的逻辑

//方法一
export function f1(){....}
//方法二
function f2(){....}
export {f2}
//方法三
export {
  f2 as streamf2
}

import

写法
//写法一
import { firstName , year  } from './....'
//写法二
import { firstName  as v1_firstname } from './...'

整体加载

// circle.js
export function area(){....}
export function circumference(){......}

//main.js
import { area, circumference } from './circle'  //这种一个个引入circle文件对外输出的接口,可实现整体加载
import * as circle from './circle'  // 利用 星号(*)指定一个对象,所有输出值都加载在这个对象上面

export default 命令

//export-default.js
export default function(){....}

/* 在引入的时候,可随意给输出变量/函数 起名
注意:此时可不用大括号;
*/
import customName from './export-default' ;

//用法二
export default function foo() {...}
//or
function foo(){....}
export default foo  // 此时可以不用大括号

//例子: 做出对比
//第一组
export deafult function crc32(){....}
import crc32 from './././'
//第二组
export function crc32(){ ...... }
import { crc32 } from './././'

export default 命令的注意点

export default 命令的实质是,输出一个名称叫 default 的变量; 所以后面不能跟随 变量声明语句
export default var a = 1; // 错误的!!!!

相关文章

网友评论

      本文标题:Module 语法——export 与 import

      本文链接:https://www.haomeiwen.com/subject/txviidtx.html