模块化
模块是独立的文件,该文件内部的所有变量外部都无法获取。如果希望获取某个变量,则需要使用export和import。
export
用于导出
//profile.js
//1
export var num=1;
export var year=2022;
//2
var num=1;
var year=2022;
export{num,year};
export *;
//3
export function multiply(x,y){
return x*y;
};
//4
function multiply(x,y){
return x*y;
}
export {multiply};
//5
var num=1;
var year=2022;
//重命名导出
export{
num as num1,
year as year1
};
//错误写法
export 1;
export num;
export function;
import
用于导入。import命令会提升到整个模块的头部,首先执行(编译阶段实习)
//1
import{ num,year } from './profile.js';
//2
import{ num as num1,year } from './profile.js';
//3
import * as aModule from './profile.js';
console.log(aModule.num);
模块整体加载所在的对象,不允许运行时改变
export default
默认导出内容使用关键字default,不需要使用花括号,且可以指定任意名称
默认导出可以和普通导出同时使用
//exportDefault.js
export const hello='hello';
export default function(){
console.log('hi');
}
//importDefault.js
//将默认导出函数命名为hi
import hi,{hello} from './exportDefault.js';
hi(); //打印hi
console.log(hello); //打印hello