• 前端模块化导入导出


    前端模块化引入与导出

    事实上,前端模块化的方式有四种

    1. AMD规范 : require.js
    2. CMD规范 : Sea.js
    3. CommonJS规范:nodejs规范
    4. ES6模块化规范

    然而,在实际项目中,用到的模块化导入导出方式并没有如此多。。。

    根据那啥二八法则,举例展示两种导出方式

    第一种方式:

    // m1.js
    
    let a = 10;
    
    function sum(a, b) {
        return a + b;
    }
    
    
    class Animal {
        constructor() {
            this.age = 20;
        }
    }
    
    exports.a = a;
    exports.sum = sum;
    exports.Animal = Animal;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    第二种方式:

    // m1.js
    
    let a = 10;
    
    function sum(a, b) {
        return a + b;
    }
    
    
    class Animal {
        constructor() {
            this.age = 20;
        }
    }
    
    module.exports = {
        a,
        sum,
        Animal
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    导入:

    const m1 = require("./m1");
    
    
    console.log(m1);            // { a: 10, sum: [Function: sum], Animal: [class Animal] }
    
    console.log(m1.a);          // 10
    console.log(m1.sum(1, 2));      // 3
    
    let cat = new m1.Animal();
    console.log(cat.age);       // 20
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    个人感觉第二种导出方式更加方便 ,需要注意的是,不推荐两种方式同时使用

    在this的指向问题上,还是需要注意的

    exports是module.exports的引用, 在js文件中有exports, 交互模式下是没有exports的

    在js文件中 this指向的是这个模块导出的对象 module.exports

    在交互模式下 this === global成立

    在js文件中 ⬇

    let aa = 10;
    exports.a = 10;
    
    
    console.log(exports);                       // { a: 10 }
    console.log(module.exports);                // { a: 10 }
    console.log(exports === module.exports);    // true
    console.log(this);                          // { a: 10 }
    console.log(this === module.exports);       // true
    console.log(this === exports);              // true
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    交互模式下⬇

    Welcome to Node.js v18.6.0.
    Type ".help" for more information.
    > this === global
    true
    > exports
    Uncaught ReferenceError: exports is not defined
    > module.exports
    {}
    > this === module.exports
    false
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
  • 相关阅读:
    如何发布自己的golang库
    【仿牛客网笔记】项目进阶,构建安全高效的企业服务——优化网站性能
    C++引用知识点超级清楚的总结
    计算机组成原理---第三章存储系统---高速缓冲存储器---选择题
    k8s--serviec,endpoint,ingress和pod
    C++11特性-可调用对象
    【PingPong_注册安全分析报告】
    1.机器学习基本概念学习笔记
    【色彩管理】ICC曲线制作教程
    switchhosts怎么配置host?
  • 原文地址:https://blog.csdn.net/m0_51126511/article/details/126201310