欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > TypeSript10 模块学习

TypeSript10 模块学习

2025/1/20 6:36:13 来源:https://blog.csdn.net/qq_37550440/article/details/141568223  浏览:    关键词:TypeSript10 模块学习

前端模块化规范是有非常多的

在es6模块化规范之前有

Commonjs - > Nodejs

// 导入
require("xxx");
require("../xxx.js");
// 导出
exports.xxxxxx= function() {};
module.exports = xxxxx;

AMD ->   requireJs

// 定义
define("module", ["dep1", "dep2"], function(d1, d2) {...});
// 加载模块
require(["module", "../app"], function(module, app) {...});

CMD ->  seaJs

define(function(require, exports, module) {
  var a = require('./a');
  a.doSomething();
  
  var b = require('./b');
  b.doSomething();
});

UMD ->  UMD是AMD和CommonJS的糅合

(function (window, factory) {
    // 检测是不是 Nodejs 环境
    if (typeof module === 'object' && typeof module.exports === "objects") {
        module.exports = factory();
    } 
    // 检测是不是 AMD 规范
    else if (typeof define === 'function' && define.amd) {
        define(factory);
    } 
    // 使用浏览器环境
    else {
        window.eventUtil = factory();
    }
})(this, function () {
    //module ...
});

es6模块化规范出来之后上面这些模块化规范就用的比较少了

现在主要使用 import export 

es6模块化规范用法

1.默认导出 和 引入

默认导出可以导出任意类型,这儿举例导出一个对象,并且默认导出只能有一个

引入的时候名字可以随便起

//导出
export default {
    a:1,
}
//引入
import test from "./test";

 2.分别导出 

export default {
    a:1,
}
 
export function add<T extends number>(a: T, b: T) {
    return a + b
}
 
export let xxx = 123
 
 
//引入
 
import obj,{xxx,add} from './test'


3.重名问题 如果 导入的时候叫add但是已经有变量占用了可以用as重命名

import obj,{xxx as bbb,add} from './test'
 
console.log(bbb)

 4.动态引入

import只能写在顶层,不能掺杂到逻辑里面,这时候就需要动态引入了

if(true){
    import('./test').then(res => {
        console.log(res)
    })
}

 5.解构导出

//a.ts

const fn = () => {

  return "fn";

};

const fn1 = () => {

  return "fn";

};

export { fn, fn1 };

//b.ts

import{ fn, fn1 } from "a.ts";

TypeSript11 tsconfig.json配置文件-CSDN博客

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com