zoukankan      html  css  js  c++  java
  • ES6 模块export import

    概述

    在 ES6 前, 实现模块化使用的是 RequireJS 或者 seaJS(分别是基于 AMD 规范的模块化库,  和基于 CMD 规范的模块化库)。

    ES6 引入了模块化,其设计思想是在编译时就能确定模块的依赖关系,以及输入和输出的变量。

    ES6 的模块化分为导出(export) @与导入(import)两个模块。

    特点

    ES6 的模块自动开启严格模式,不管你有没有在模块头部加上 use strict;。

    模块中可以导入和导出各种类型的变量,如函数,对象,字符串,数字,布尔值,类等。

    每个模块都有自己的上下文,每一个模块内声明的变量都是局部变量,不会污染全局作用域。

    每一个模块只加载一次(是单例的), 若再去加载同目录下同文件,直接从内存中读取。

    基本用法:

    定义一个export.js

    let name = "Jack";
    
    let age = 11;
    
    let func = function(){
    
            return `姓名:${name},年龄:${age}`
    
    }
    
    let myClass =  class myClass {
    
        static a = "呵呵";
    
    }
    
    export {name, age, func, myClass}
    <script type="module">
    
        import {name, age, func, myClass} from "./export.js";
    
    
    
        console.log(name);
    
        console.log(age);
    
        console.log(func());
    
        console.log(myClass.a );
    
    </script>

    注意 type是module;

    as 的用法

    默认的话,导出的和导入的名称是一样;一般的话也这么干,不过假如要改成名称,搞个别名,我们用as来搞;

    <script type="module">
    
        import {name as myName, age as myAge, func as MyFunc, myClass as mC} from "./export.js";
    
    
    
        console.log(myName);
    
        console.log(myAge);
    
        console.log(MyFunc());
    
        console.log(mC.a );
    
    </script>

    运行效果一样;

    export default 命令

    在一个文件或模块中,export、import 可以有多个,export default 仅有一个。

    export default 中的 default 是对应的导出接口变量。

    通过 export 方式导出,在导入时要加{ },export default 则不需要。

    export default 向外暴露的成员,可以使用任意变量来接收。

    最简单的,到处一个变量:

    let name = "Jack";
    
    export default name

    因为导出是单个,花括号省略;

    <script type="module">
    
        import name from "./export.js";
    
        console.log(name);
    
    </script>

    导入的地方,花括号也省略;

    一般开发,比如vue,导出的是一个组件对象;

    我们新建一个student.js 

    export default {
    
        name:'Jack',
    
        age:20,
    
        getInfo(){
    
            return `姓名:${this.name},年龄:${this.age}`
    
        }
    
    }
    <script type="module">
    
        import student from "./student.js";
    
    
    
        console.log(student);
    
        console.log(student.getInfo())
    
    
    
    </script>

  • 相关阅读:
    sqlserver 角色
    SqlServer 连接字符串多种配置
    SqlServer Link 链接服务器的使用
    web.config 加密/解密
    C# 设置开机自动启动(注册表方式)
    mono 3.4.0 make install的时候出现"找不到 Microsoft.Portable.Common.targets 文件”的错误提示解决方法
    Jexus V5.5.1 在linux的使用方法
    WCF 客户端解决大数据量传输配置
    POPTEST培训:web自动化测试之DOM
    自动化测试培训:设计和实现分布式QTP调用
  • 原文地址:https://www.cnblogs.com/zsh-blogs/p/12966940.html
Copyright © 2011-2022 走看看