兼收并蓄 TypeScript - 类: 模块

源码 https://github.com/webabcd/TypeScriptDemo
作者 webabcd

兼收并蓄 TypeScript - 类: 模块

示例如下:

module\main.ts

/**
 * 本例用于演示 import, export
 */

// 从指定的模块中导入指定的被 export 的变量或函数或对象
import { name, hello } from './a';
// 从指定的模块中导入指定的被 export 的变量或函数或对象
import { name_b, hello_b } from './b';
// 从指定的模块中导入指定的被 export 的变量或函数或对象(并重命名)
import { name as name_c, hello as hello_c } from './c';
// 从指定的模块中导入指定的被 export 的变量或函数或对象(并重命名)
import { name as name_d, hello as hello_d } from './d';
// 从指定的模块中导入被 export default 的变量或函数或对象,并为其命名
// 注:对于 export default 导出的对象,在 import 的时候不需要加 {}
import obj_e from './e';
// 从指定的模块中导入被 export default 的变量或函数或对象,并为其命名
// 注:对于 export default 导出的对象,在 import 的时候不需要加 {}
import obj_f from './f';
// 从指定的模块中导入指定的被 export 的变量或函数或对象
import { name as name_g, hello as hello_g }  from './g';
// 从指定的模块中导入被 export 的全部内容
import * as obj_h from './h';

console.log(`a: ${name} ${hello()}`);
console.log(`b: ${name_b} ${hello_b()}`);
console.log(`c: ${name_c} ${hello_c()}`);
console.log(`d: ${name_d} ${hello_d()}`);
console.log(`e: ${obj_e.name} ${obj_e.hello()}`);
console.log(`f: ${obj_f.name} ${obj_f.hello()}`);
console.log(`g: ${name_g} ${hello_g()}`);
console.log(`h: ${obj_h.name} ${obj_h.hello()}`);

// 将 './i' 文件导入并编译
import './i';

module\dynamicImport.ts

/**
 * 本例用于演示模块的动态导入(es2020 新特性)
 */

setTimeout(async () => { 
    // 模块的动态导入
    const a = await import('./a.js');
    console.log(`${a.name} ${a.hello()}`); // name hello
}, 3000);

module\a.ts

let name = "name";
let hello = function() {
    return "hello"
};

// 导出指定的变量或函数或对象
export { name, hello }

module\b.ts

let name = "name";
let hello = function() {
    return "hello"
};

// 导出指定的变量或函数或对象(并重命名)
export { name as name_b, hello as hello_b};

module\c.ts

// 导出指定的变量或函数或对象
export let name = "name", hello = ()=> { return "hello"; };

module\d.ts

// 导出指定的变量或函数或对象
// 一个模块中可以有多个 export
export let name = "name";
export let hello = ()=> { return "hello"; };

module\e.ts

// 导出 default 变量或函数或对象
// 一个模块中只能有一个 export default
export default {
    name : "name",
    hello:function() {
        return "hello";
    }
}

module\f.ts

let obj = {
    name : "name",
    hello:function() {
        return "hello";
    }
}

// 导出 default 变量或函数或对象
// 一个模块中只能有一个 export default
export default obj;

module\g.ts

// 从指定的模块中导出全部内容
export * from './a';

module\h.ts

let name = "name";
let hello = function() {
    return "hello"
};

// 导出指定的变量或函数或对象
export { name, hello }

module\i.ts

let myName = "i am webabcd";
console.log(myName);

源码 https://github.com/webabcd/TypeScriptDemo
作者 webabcd

posted @ 2024-09-20 12:21  webabcd  阅读(1)  评论(0编辑  收藏  举报