js 模块导出导入 整理

模块化

CommonJS

导出:

modules.exports={
	flag: true,
    test(a, b){
        return a+b
    }
}

导入:

let {flag, test} = require('moduleA');
//等价于
let _mA = require('moduleA');
let test = _mA.test;
let flag = _mA.flag;

ES6的export基本使用

导出:

export let name = "aaa";
export let age = 18;
export let height = 1.8;
//或者
let name = "aaa";
let age = 18;
let height = 1.8;
export {name, age, height}
//函数和类也按照这样的方式导出(把类名和函数名当变量使用

//export default 在 导入者希望可以自己命名导入的功能 的情况下使用
//info.js
export default function(){
    console.log('hello');
}
//导入时命名为myFunc
import myFunc from './info.js'

导入:import使用

需要先在html文件中引入两个js文件,类型设置为module

<script src="info.js" type="module"></script>
<script src="mian.js" type="module"></script>

import指令用于导入模块中的内容:

import {name, age, height} from './info.js'
console.log(name, age, height);

如果觉得{name, age, height}麻烦,可以使用*将模块所有export都导入,通常需要起一个别名,方便后续使用:

import * as info from './info.js'
console.log(info.name, info.age, info.height);
posted @ 2020-12-21 13:43  团叽  阅读(274)  评论(0编辑  收藏  举报