What does the TypeScript “lib” option really do?

若如初见. 提交于 2019-11-30 12:43:47

Typescript does not have any built-in types all types come from a set of base definitions (located in the lib folder in the typescript install directory). By default the target defines which libs are included. For example the docs state:

Note: If --lib is not specified a default list of librares are injected. The default libraries injected are:

► For --target ES5: DOM,ES5,ScriptHost

► For --target ES6: DOM,ES6,DOM.Iterable,ScriptHost

The basic idea is that while target is deals with language features (more specifically which language features need to be down compiled, ex: for-of, or arrow functions), the lib option deals with what facilities the runtime environment has (ie. what built-in objects look like, what they are).

Ideally the default libs for a given target should be used. We may, however, have an environment which supports some of the runtime facilities but not the language features, or we may target runtime with a lower es version and poly-fill some of the runtime facilities, which can be in general done for some things (ex: Promises).

Remember, TS never injects polyfills in your code. It's not its goal. Complementing the answer above:

target tells TS which ES specification you want the final code to support. If you configure it as ES5, TS will down compile the syntactic features to ES5, so any arrow functions (() => {}) in the code will be transformed to functions. But it's also going to assume your browser supports all ES5 functional features at runtime. For example, if you have Array.isArray (an ES5 feature) in your code and you try to open your website in IE8, it's going to break because it does not support this. You have to polyfill it if you want to support that browser.

lib tells TS what type definitions to include in your project. If you have "target": "es5", the default value for lib will be ["dom", "es5", "ScriptHost"]. It means what functional features the browser will support at runtime. If you add any polyfills for things above your target, is here where you configure this extra support.

Example: You need to support IE11 and you have Promise in your code. IE11 does not support promises, so you have to import yourself a polyfill in your code, and then tell TS:

"target": "es5",
"lib": ["es5", "dom", "ScriptHost", "es2015.promise"]
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!