• 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);
    
  • 相关阅读:
    软件工程 团队博客第二阶段成绩
    现代软件工程 10 绩效管理
    现代软件工程讲义 1 软件工程概论
    现代软件工程讲义 0 教学方法
    软件工程 敏捷的酒后问答
    我传递了错误的信息
    起跑点上
    输在起跑点上?
    好可怕的假相
    浪子回头
  • 原文地址:https://www.cnblogs.com/peekapoooo/p/14167483.html
Copyright © 2020-2023  润新知