JS模块化方案(4)之ES6模块化

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/TDCQZD/article/details/82467301

一、基本介绍

不同于CommonJS等规范。ES6 模块的设计思想是尽量的静态化,使得编译时就能确定模块的依赖关系,以及输入和输出的变量。

ES6 模块不是对象,而是通过export命令显式指定输出的代码,再通过import命令输入。

1、export命令
个模块就是一个独立的文件。该文件内部的所有变量,外部无法获取。如果你希望外部能够读取模块内部的某个变量,就必须使用export关键字输出该变量。

export var firstName = 'Michael'; //test.js
export var lastName = 'Jackson';
export var year = 1958;

export的写法,除了像上面这样,还有另外一种:
它与前一种写法是等价的,但是应该优先考虑使用这种写法。因为这样就可以在脚本尾部,一眼看清楚输出了哪些变量。

var firstName = 'Michael'; //test.js
var lastName = 'Jackson';
var year = 1958;
export {firstName, lastName, year};

export命令除了输出变量,还可以输出函数或类(class)

export function multiply(x, y) {
  return x * y;
};

需要特别注意的是,export命令规定的是对外的接口,必须与模块内部的变量建立一一对应关系。
下面两种写法都会报错,因为没有提供对外的接口。
第一种写法直接输出 1,第二种写法通过变量m,还是直接输出 1。1只是一个值,不是接口。

export 1;// 报错   
var m = 1;export m; // 报错
function f() {}  export f; // 报错
        正确的写法是下面这样:
export var m = 1;   export function f() {};   // 写法一
var m = 1;    export {m}  
function f() {};  export {f};                   // 写法二

最后,export命令可以出现在模块的任何位置,只要处于模块顶层就可以。如果处于块级作用域内,就会报错

2、import命令
使用export命令定义了模块的对外接口以后,其他 JS 文件就可以通过import命令加载这个模块. import命令接受一对大括号,里面指定要从其他模块导入的变量名。大括号里面的变量名,必须与被导入模块(test.js)对外接口的名称相同。import命令具有提升效果,会提升到整个模块的头部,首先执行。

import {firstName, lastName, year} from './test.js';

如果想为输入的变量重新取一个名字,import命令要使用as关键字,将输入的变量重命名。

import { lastName as surname } from './test.js';  

import命令输入的变量都是只读的,因为它的本质是输入接口。也就是说,不允许在加载模块的脚本里面,改写接口

import {a} from './xxx.js'
a = {}; // Syntax Error : 'a' is read-only; 

由于import是静态执行,所以不能使用表达式和变量,这些只有在运行时才能得到结果的语法结构

// 报错
import { 'f' + 'oo' } from 'my_module';

// 报错
let module = 'my_module';
import { foo } from module;

// 报错
if (x === 1) {
  import { foo } from 'module1';
} else {
  import { foo } from 'module2';
}

整体模块的加载,即用星号(*)指定一个对象,所有输出值都加载在这个对象上。

import * as circle from './circle';

3、export default命令
从前面的例子可以看出,使用import命令的时候,用户需要知道所要加载的变量名或函数名,否则无法加载。但是,用户肯定希望快速上手,未必愿意阅读文档,去了解模块有哪些属性和方法。Default本身就是变量,export default命令的本质是将后面的值,赋给default变量。

export default function () {console.log('foo');} //正确
export default function foo() {console.log('foo');} //正确

function foo() {console.log('foo');}
export default foo;//正确

export default 42; //正确
export 42; // 报错
export default var a = 1; // 错误

一个模块只能有一个默认输出,因此export default命令只能使用一次。
所以,import命令后面可以不用加{},因为只可能唯一对应export default命令

import customName from './xxx';    customName(); //foo 

二、使用流程:

1、模块定义

export function common(){
   return "common";
}

2、模块引用

import {common} from "./common/common.js";
import * as damu from "./damu.js";
import {a as aa,b as bb} from "./02.js";

3、界面加载模块
webpack 打包JS文件

webpack  ./index.js  ./dist/index.js
<script src="./dist/index.js"></script>

三、使用细节和注意事项

1、for-in 运作在严格模式与非严格模式 内部变量提升的区别

<script type="text/javascript">
   // "use strict";
   app();

   function app(){
      var obj={
         a:"a",
         b:"b",
         c:"c"
      }

      for( item in obj){
         // console.log(item)
      }
   }

   console.log(item)
/*
严格模式 :c 
非严格模式 :报错 Uncaught ReferenceError: item is not defined
*/
</script>

2、静态分析,import不能做运算处理。
如下错误代码

import { 'f' + 'oo' } from 'my_module';

3、export 匿名函数时使用default

03.js
export function (){};//报错

export default function (){};/正确
import obj from "./03.js";
console.log(obj)

四、ES6模块化总结

1、经典方案

    import {标识,标识} from "路径"

    export 代码块
    export 代码块
    export 代码块

优缺点:解决了依赖问题,但没有解决命名冲突。

2、优化方案一

  import * as 命名空间 from "路径"

优缺点:解决了依赖于命名冲突的问题;但是 导出的代码块过于混乱。

3、优化方案二

    export {
            代码块,
            代码块,
            代码块
        }
    import * as 命名空间 from "路径"

**优缺点:**import 导出过于麻烦.

4、优化方案三——default
export 提供了一个语法糖 default


        export default {
            代码块,
            代码块,
            代码块
        }
  import 任意标识 from "路径"

五、案例

index.html

    <script src="./dist/index.js"></script>

common.js

export function common(){
    return "common";
}

damu.js

import {common} from "./common/common.js";

export function A(){
    //require函数的返回值:define中的module.exports
    console.log("A from damu&"+ common());
}

export function B(){
    console.log("B from damu&"+ common());
}

export function C(){
    console.log("C from damu&"+ common());
}




hsp.js

import {common} from "./common/common.js";

export function A(){
    //require函数的返回值:define中的module.exports
    console.log("A from hsp&"+ common());
}

export function B(){
    console.log("B from hsp&"+ common());
}

export function C(){
    console.log("C from hsp&"+ common());
}



tg.js


import {common} from "./common/common.js";
 function A(){
    //require函数的返回值:define中的module.exports
    console.log("A from tg&"+ common());
}

 function B(){
    console.log("B from tg&"+ common());
}

 function C(){
    console.log("C from tg&"+ common());
}

export {
    A,
    B,
    C
}

入口的index.js

import * as damu from "./damu.js";
import * as hsp from "./hsp.js";
import * as tg from "./tg.js";
window.onload=function(){
    damu.A();
    damu.B();
    damu.C();

    hsp.A();
    hsp.B();
    hsp.C();

    tg.A();
    tg.B();
    tg.C();
}

打包后的index.js

/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/        // Check if module is in cache
/******/        if(installedModules[moduleId]) {
/******/            return installedModules[moduleId].exports;
/******/        }
/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            i: moduleId,
/******/            l: false,
/******/            exports: {}
/******/        };
/******/
/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.l = true;
/******/
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, {
/******/                configurable: false,
/******/                enumerable: true,
/******/                get: getter
/******/            });
/******/        }
/******/    };
/******/
/******/    // getDefaultExport function for compatibility with non-harmony modules
/******/    __webpack_require__.n = function(module) {
/******/        var getter = module && module.__esModule ?
/******/            function getDefault() { return module['default']; } :
/******/            function getModuleExports() { return module; };
/******/        __webpack_require__.d(getter, 'a', getter);
/******/        return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/    __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = 1);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = common;
function common(){
    return "common";
}



/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__damu_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__hsp_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__tg_js__ = __webpack_require__(4);



window.onload=function(){
    __WEBPACK_IMPORTED_MODULE_0__damu_js__["a" /* A */]();
    __WEBPACK_IMPORTED_MODULE_0__damu_js__["b" /* B */]();
    __WEBPACK_IMPORTED_MODULE_0__damu_js__["c" /* C */]();

    __WEBPACK_IMPORTED_MODULE_1__hsp_js__["a" /* A */]();
    __WEBPACK_IMPORTED_MODULE_1__hsp_js__["b" /* B */]();
    __WEBPACK_IMPORTED_MODULE_1__hsp_js__["c" /* C */]();

    __WEBPACK_IMPORTED_MODULE_2__tg_js__["a" /* A */]();
    __WEBPACK_IMPORTED_MODULE_2__tg_js__["b" /* B */]();
    __WEBPACK_IMPORTED_MODULE_2__tg_js__["c" /* C */]();
}


/***/ }),
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = A;
/* harmony export (immutable) */ __webpack_exports__["b"] = B;
/* harmony export (immutable) */ __webpack_exports__["c"] = C;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__common_common_js__ = __webpack_require__(0);


function A(){
    //require函数的返回值:define中的module.exports
    console.log("A from damu&"+ __WEBPACK_IMPORTED_MODULE_0__common_common_js__["a" /* common */]());
}

function B(){
    console.log("B from damu&"+ __WEBPACK_IMPORTED_MODULE_0__common_common_js__["a" /* common */]());
}

function C(){
    console.log("C from damu&"+ __WEBPACK_IMPORTED_MODULE_0__common_common_js__["a" /* common */]());
}






/***/ }),
/* 3 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = A;
/* harmony export (immutable) */ __webpack_exports__["b"] = B;
/* harmony export (immutable) */ __webpack_exports__["c"] = C;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__common_common_js__ = __webpack_require__(0);


function A(){
    //require函数的返回值:define中的module.exports
    console.log("A from hsp&"+ __WEBPACK_IMPORTED_MODULE_0__common_common_js__["a" /* common */]());
}

function B(){
    console.log("B from hsp&"+ __WEBPACK_IMPORTED_MODULE_0__common_common_js__["a" /* common */]());
}

function C(){
    console.log("C from hsp&"+ __WEBPACK_IMPORTED_MODULE_0__common_common_js__["a" /* common */]());
}





/***/ }),
/* 4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return A; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return B; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return C; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__common_common_js__ = __webpack_require__(0);


 function A(){
    //require函数的返回值:define中的module.exports
    console.log("A from tg&"+ __WEBPACK_IMPORTED_MODULE_0__common_common_js__["a" /* common */]());
}

 function B(){
    console.log("B from tg&"+ __WEBPACK_IMPORTED_MODULE_0__common_common_js__["a" /* common */]());
}

 function C(){
    console.log("C from tg&"+ __WEBPACK_IMPORTED_MODULE_0__common_common_js__["a" /* common */]());
}





/***/ })
/******/ ]);

猜你喜欢

转载自blog.csdn.net/TDCQZD/article/details/82467301