javaScript 基础知识汇总 (十五)

1、模块简介

  什么是模块:

  模块就是一个文件,一个脚本,通过关键字export 和 import 交换模块之间的功能。

  export 关键字表示在当前模块之外可以访问的变量和功能。

  import 关键字允许从其他模块中导入一些诸如函数之类的功能。

  使用示例:

  文件 say.js

  export function sayHi(user)

    return `Hello ,${user}!`;

  }

  文件index.html

  <!doctype html>

  <script type="module">

    import {sayHi} from './say.js';

    document.body.innerHTML = sayHi('John");

  </script>

  核心模块功能

    1)始终使用 use strict

    2)模块级作用域

      每个模块都有自己的作用域

    3)模块代码仅在第一次导入时解析

  顶级 “this" 是未定义的(undefined)

    在模块中的this与模块中的区别是 普通脚本中的this 是window 而模块中的this则是undefined

  <script>

    alert(this);//window

  </script>

  <script type = "moudle">

    alert(this);//undefined

  </script>

  模块脚本是延迟解析的

  • 外部模块脚本 <script type="module" src="..."> 不会阻塞 HTML 的解析,它们与其他资源并行加载。
  • 直到 HTML 文档完全解析渲染后(即使模块脚本比 HTML 先加载完成),模块脚本才会开始运行。
  • 执行脚本的相对顺序:在前面的先执行。

  不允许裸模块

    import {sayHi} from 'sayHi'; // Error,“裸”模块
    // 模块必须提供路径,例如 './sayHi.js'

2、模块的导入导出

  声明前导出  

  
// 导出数组
export let months = ['Jan', 'Feb', 'Mar','Apr', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

// 导出 const 声明的变量
export const MODULES_BECAME_STANDARD_YEAR = 2015;

// 导出类
export class User {
  constructor(name) {
    this.name = name;
  }
}

  声明后导出

1 function sayHi(User){
2     alert(`Hello,${User}!`);
3 }
4 fucntion sayBye(user)
5     alert(`bye,${user}!`);
6 }
7 export{sayHi,sayBye};

  指明导入的内容

 

1 // 📁 main.js
2 import {sayHi, sayBye} from './say.js';
3 
4 sayHi('John'); // Hello, John!
5 sayBye('John'); // Bye, John!

  全部导入

1 // 📁 main.js
2 import * as say from './say.js';
3 
4 say.sayHi('John');
5 say.sayBye('John');

  导入和导出通过 as给对象起别名

 

 1 // 📁 main.js
 2 import {sayHi as hi, sayBye as bye} from './say.js';
 3 
 4 hi('John'); // Hello, John!
 5 bye('John'); // Bye, John!
 6 
 7 // 📁 say.js
 8 ...
 9 export {sayHi as hi, sayBye as bye};
10 
11 // 📁 main.js
12 import * as say from './say.js';
13 
14 say.hi('John'); // Hello, John!
15 say.bye('John'); // Bye, John!

 

 

3、动态导入

  import() 函数

 1 say.js
 2 
 3 export function hi() {
 4   alert(`Hello`);
 5 }
 6 
 7 export function bye() {
 8   alert(`Bye`);
 9 }
10 
11 export default function() {
12   alert("Module loaded (export default)!");
13 }
14 
15 index.html
16 
17 <!doctype html>
18 <script>
19   async function load() {
20     let say = await import('./say.js');
21     say.hi(); // Hello!
22     say.bye(); // Bye!
23     say.default(); // Module loaded (export default)!
24   }
25 </script>
26 <button onclick="load()">Click me</button>

 

  

posted @ 2019-09-12 10:58  小七要走  阅读(285)  评论(0编辑  收藏  举报