05-模块化

Huxzhi大约 2 分钟react18

作为一个模块,我们不希望模块中所有的内容都暴露给外部 作为导入方,也不希望导入无用的变量

export(导出)

导出用来决定一个模块中哪些内容可以被外部查看

导出分成两种:

默认导出

  • 语法:
    export default xxx;
  • 一个模块中只能有一个默认导出

命名导出

export const A;

// 导出变量(命名导出)  
export let name1, name2,, nameN;   
export let name1 =, name2 =,, nameN;// 导出函数(命名导出)  
export function functionName(){...}// 导出类(命名导出)  
export class ClassName {...}// 导出一组  
export { name1, name2,, nameN };// 重命名导出  
export { variable1 as name1, variable2 as name2,, nameN };// 解构赋值后导出  
export const { name1, name2: bar } = o;// 默认导出  
export default expression;  
export default function () {} // also class, function*  
export default function name1() {} // also class, function*  
export { name1 as default,};// 聚合模块  
export * from …; // 将其他模块中的全部内容导出(除了default)  
export * as name1 from …; // ECMAScript® 2O20 将其他模块中的全部内容以指定别名导出  
export { name1, name2,, nameN } from …; // 将其他模块中的指定内容导出  
export { import1 as name1, import2 as name2,, nameN } from …; // 将其他模块中的指定内容重命名导出  
export { default,} from …;

import(导入)

  • 导入用来将外部模块中的内容导入到当前模块中
<!--
    默认情况下,script标签中不能使用import语句,
        如果想让其支持模块化,必须设置script的type属性为module
-->
<script type="module">

    // 导入m1模块中的默认模块
    // import haha from './m1.js';

    // 导入m1模块中的b和c
    // import {b as hello, c, obj, fn} from './m1.js';

    import a, {b, c, obj, fn} from './m1.js';
    console.log(a, b, c, obj);

    fn();

</script>

导入默认模块

import a from './m1.js';

  • 导入默认模块时,变量名可以自主指定,无需和模块中的变量名对应
  • 在网页中导入模块时,模块的路径必须写完整(/./../ 开头,扩展名也得写上)

导入指定内容

{} 包裹,和模块中的变量名对应

import {b, c as} from './m1.js';

以指定别名引入模块中的指定内容

import { export1 as alias1 } from "module-name";

导入默认及指定内容

第一逗号前是 默认导出,后面是 命名导出 import a, {b, c, obj, fn} from './m1.js';