当前位置:网站首页>LayaBox---TypeScript---structure
LayaBox---TypeScript---structure
2022-08-04 21:22:00 【Gragra】
目录
2.Identify the type of library
2.2Identify global libraries from code
2.4Identify modular libraries from code
5.1Identify globally modified modules
6.1Depends on the global library
8.3 ES6The effect of module call signatures
1.介绍
一般来讲,你组织The way the file is declared depends on how the library is used. 在JavaScriptThere are many ways to use a library,This requires you to write declaration files to match them.This section will help you understand common library formats and how to write the correct declaration files for each format.
2.Identify the type of library
Identifying the type of library is the first step in writing a declaration file.
2.1全局库
全局Libraries are those that can be accessed under the global namespace(例如:No need to use any formimport
). Many libraries simply expose one or more global variables. 比如,如果你使用过 jQuery,$
Variables can be referenced simply enough:
$(() => { console.log('hello!'); } );
You'll often see how in the global library's guide documentHTMLReference the library with a script tag:
<script src="http://a.great.cdn.for/someLib.js"></script>
目前,Most of the popular globally accessible libraries actually start with UMDwritten in the form of a library(见后文). UMDThe documentation for the library is indistinguishable from the documentation for the global library. Before writing the global declaration file,Be sure to check to see if the library really isn'tUMD.
2.2Identify global libraries from code
The code for a global library is usually quite simple. 一个全局的“Hello, world”Libraries might look like this:
function createGreeting(s) {
return "Hello, " + s;
}
或这样:
window.createGreeting = function(s) {
return "Hello, " + s;
}
When you look at the source code of the global library,you usually see:
- 顶级的
var
语句或function
声明- One or more assignment statements to
window.someName
- 假设DOMraw value like
document
或window
是存在的你不会看到:
- Check if or how the module loader is used,比如
require
或define
- CommonJS/Node.jsStyle import eg
var fs = require("fs");
define(...)
调用- The documentation explains how to do it
require
or import this library
2.3模块化库
一些库只能工作在模块加载器的环境下. 比如,像
express
只能在Node.js里工作所以必须使用CommonJS的require
函数加载.
ECMAScript 2015(也就是ES2015,ECMAScript 6或ES6),CommonJS和RequireJS具有相似的导入一个模块的表示方法. 例如,对于JavaScript CommonJS (Node.js),有下面的代码:
var fs = require("fs");
对于TypeScript或ES6,importKeywords also have the same effect:
import fs = require("fs");
You will usually see the following instructions in the documentation of the modular library:
var someLib = require('someLib');
或
define(..., ['someLib'], function(someLib) {
});
2.4Identify modular libraries from code
The module library will contain at least one of the following representative entries:
- Unconditional call
require
或define
- 像
import * as a from 'b';
orexport c;
这样的声明- 赋值给
exports
或module.exports
They are rarely included:
- 对
window
或global
的赋值
许多流行的Node.jsLibraries are all this modular,例如express,gulp和 request.
UMD模块是指那些既可以作为模块使用(通过导入)又可以作为全局(在没有模块加载器的环境里)使用的模块. 许多流行的库,比如 Moment.js,就是这样的形式. 比如,在Node.js或RequireJS里,你可以这样写:
import moment = require("moment");
console.log(moment.format());
However, in a pure browser environment you can also write this:
console.log(moment.format());
2.5识别UMD库
UMD模块会检查是否存在模块加载器环境.
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define(["libName"], factory);
} else if (typeof module === "object" && module.exports) {
module.exports = factory(require("libName"));
} else {
root.returnExports = factory(root.libName);
}
}(this, function (b) {
If you see it in the source code of the librarytypeof define
,typeof window
,或typeof module
这样的测试,Especially at the top of the file,Well it's almost oneUMD库.
UMDPasses are often included in the library's documentationrequire
“在Node.js里使用”例子, 和“在浏览器里使用”的例子,展示如何使用 <script>
tag to load the script.
Most popular libraries can now be used as suchUMD包. 比如 jQuery,Moment.js,lodash和许多其它的.
2.6模版
There are three modules available for modules, module.d.ts, module-class.d.ts and module-function.d.ts.
使用module-class.d.tsIf the module can be usednew
来构造:
var x = require("bar");
// Note: using 'new' operator on the imported variable
var y = new x("hello");
3.模块插件或UMD插件
一个模块插件It is possible to change the structure of a module(UMD或模块).
例如,在Moment.js里, moment-range
添加了新的range
方法到monent
对象.
模版:使用module-plugin.d.ts模版.
4.全局插件
一个全局插件is the global code,They change the structure of the global object. 对于 Globally modified modules,There is a possibility of conflict at runtime.
比如,Some libraries goArray.prototype
或String.prototype
add a new method.
4.1Identify global plugins
var x = "hello, world";
// Creates new methods on built-in types
console.log(x.startsWithHello());
var y = [1, 2, 3];
// Creates new methods on built-in types
console.log(y.reverseAndSort());
模版:同上
5.Globally modified modules
当一个Globally modified modules被导入的时候,They change the value in the global scope. 比如,Some libraries exist which add new members to
String.prototype
when importing them.
This mode is dangerous,Because it may cause runtime conflicts, But we can still write declaration files for them.
5.1Identify globally modified modules
Globally modified modules can usually be easily identified from their documentation. 通常来讲,They are similar to global plugins,但是需要 require
Called to activate their effects.
// 'require' call that doesn't use its return value
var unused = require("magic-string-time");
/* or */
require("magic-string-time");
var x = "hello, world";
// Creates new methods on built-in types
console.log(x.startsWithHello());
var y = [1, 2, 3];
// Creates new methods on built-in types
console.log(y.reverseAndSort());
模版:使用global-modifying-module.d.ts模版.
6.使用依赖
6.1Depends on the global library
If your library depends on some global library,使用/// <reference types="..." />
指令:
/// <reference types="someLib" />
function getThing(): someLib.thing;
6.2依赖模块
If your library depends on modules,使用import
语句:
import * as moment from "moment";
function getThing(): moment;
7.依赖UMD库
7.1from the global library
If your global library depends on a UMD模块,使用/// <reference types
指令:
/// <reference types="moment" />
function getThing(): moment;
7.2from a module orUMD库
If your module or UMDLibraries depend on oneUMD库,使用import
语句:
import * as someLib from 'someLib';
不要使用/// <reference
指令去声明UMD库的依赖!
8.补充说明
8.1防止命名空间冲突
️注意:When writing a global declaration file,Allows to define many types in the global scope. We are very unjust to do so,When there are many declaration files in a project,It causes naming conflicts that cannot be handled.
A simple rule is to use library-defined global variable names to declare namespace types. 比如,The library defines a global value cats
,你可以这样写:
declare namespace cats {
interface KittySettings { }
}
不要
// at top-level
interface CatsKittySettings { }
For declaration file users,It is guaranteed that the library is being converted into UMDwithout any destructive changes.
8.2 ES6Modular plugin effects
Some plugins add or modify the exports section of an existing top-level module. 当然这在CommonJSand other loaders are allowed,ESModules are considered immutable so this pattern is not feasible. 因为TypeScriptIt is possible to not predict the loader type,So there is no guarantee at compile time,But if the developer wants to goES6This should be noted on module loaders.
8.3 ES6The effect of module call signatures
Many popular libraries,比如Express,Exposes itself as a callable function. 比如,典型的Express使用方法如下:
import exp = require("express");
var app = exp();
在ES6in the module loader,顶层的对象(这里以exp
导入)Can only have attributes; The top-level module object 永远不能被调用. A very common solution is to define one default
Export to a callable/Constructable object; After a while the module loader helper tool can detect this by itself and use it default
Export to replace top-level objects.
边栏推荐
猜你喜欢
随机推荐
【1403. 非递增顺序的最小子序列】
web漏洞扫描器-awvs
stm32mp157系统移植 | 移植ST官方5.10内核到小熊派开发板
【2022杭电多校5 1012题 Buy Figurines】STL的运用
win10 uwp use WinDbg to debug
1、File对象学习
无代码平台字段设置:基础设置入门教程
C语言之实现扫雷小游戏
88. (the home of cesium) cesium polymerization figure
经验分享|盘点企业进行知识管理时的困惑类型
Win11如何开启Telnet客户端?
[Teach you to use the serial port idle interrupt of the STM32HAL library]
js的new Function()常用方法
经验分享|盘点企业进行知识管理时的困惑类型
【随记】新一天搬砖 --20220727
proe和creo的区别有哪些
dotnet compress Stream or file using lz4net
Red team kill-free development practice of simulated confrontation
3. Byte stream and character stream of IO stream
Yolov7:Trainable bag-of-freebies sets new state-of-the-art for real-time objectdetectors