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)