search
HomeWeb Front-endJS TutorialDetailed explanation of the use of js bundled TypeScript declaration

Detailed explanation of the use of js bundled TypeScript declaration

Apr 28, 2018 pm 01:45 PM
javascripttypescriptDetailed explanation

This time I will bring you a detailed explanation of the use of js bundled TypeScript declaration. What are the precautions for js bundled TypeScript declaration. The following is a practical case, let's take a look.

Preface

TypeScript is a superset of the JavaScript type. This is a sentence introduced in the TypeScript documentation. So are they connected?

My understanding is that TypeScript introduces the characteristics of a strongly typed language based on JavaScript. Developers use TypeScript syntax for programming development, and finally convert TypeScript into JavaScript through conversion tools.

Using TypeScript can avoid the pitfalls of weakly typed languages ​​caused by developing on native JavaScript. (What should I enter? What should I return after the call? Let’s take a look at the source code...)

Hmm! Very good, strongly typed JavaScript, very good. However, I can’t bear the meticulous humanistic care of many libraries in NPM o(TヘTo)

Don’t be afraid, many libraries now quietly support TypeScript. Even if they have no intention of supporting it, there are still big guys who make selfless contributions. Quietly help these libraries support TypeScript

This leads to the topic of this article, the TypeScript declaration file. I think it is a header file for the JavaScript library similar to the C language. Its existence is to help TypeScript introduce the JavaScript library.

What is a declaration file?

is very similar to C/C *.h header files: when you reference a third-party library (.lib/.dll/ .so/.a/.la), the C/C compiler cannot automatically recognize the exported names and function type signatures in the library, which requires the use of header files for interface declarations.

Similarly, the TypeScript declaration file is a TypeScript code file with the .d.ts suffix, but its role is to describe the type information of all exported interfaces within a JavaScript module (in a broad sense).

For the writing and specifications of TypeScript declaration files, please refer to the following official documents and excellent blog posts:

  • https://www.tslang. cn/docs/handbook/declaration-files/introduction.html

  • http://www.jb51.net/article/138217.htm

According to the official documentation, there are the following two bundling methods:

  • Bundled with your npm package

  • Publish to npm The @types organization

is bundled with the npm package as mentioned above. Developers can use it directly after npm install a library in the ts project and import it in the code file.

When some libraries are not officially maintained, you can use the second method. After npm installs a library, execute npm install @types/library name to install the declaration file of the library. The principle is that after TypeScript version 2.0, when you import a library and the specified library is not found in the configured include path, it will look for the library in @types of node_modules.

Generally speaking, the official recommendation is the first way to write the release statement document. Let me directly use an example to demonstrate the first bundling method.

Example

First initialize the TypeScript project, The directory structure is as follows:

tsconfig.json configuration is as follows:

{
 "compilerOptions": {
 "target": "es5",
 /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
 "module": "commonjs",
 /* Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
 "allowJs": true,
 "outDir": "./dist",
 /* Redirect output structure to the directory. */
 /* Allow javascript files to be compiled. */
 "strict": true /* Enable all strict type-checking options. */
 },
 "include": [
 "src/**/*"
 ]
}

As you can see, I wrote a module a and bundled a declaration file with it. The content of module a, that is, src/a/index.js is as follows :

const NAME = 'A';
let call = (who) => {
 console.log('Hello ' + who + '! I am ' + NAME);
}
export default {
 call
}

The declaration file is src/a/index.d.ts and the content is as follows:

declare namespace a {
 function call(who: string): void;
}
export default a;

At this time, we can enter the entry file src/index. ts introduces a module:

import a from './a';
a.call('Pwcong');

After executing tsc on the command line, js code can be generated in the directory dist:

Execute the command node ./dist/index .js can get the corresponding correct output.

We then simulate importing the released NPM library, create directory b under the node_modules directory, and initialize the Node project. At this time, the directory structure is as follows:

其中 node_modules/b/types/package.json 内容如下:

{
 "name": "b",
 "version": "1.0.0",
 "main": "./src/index.js",
 "types": "./types/index.d.ts"
}

node_modules/b/src/index.js 内容如下:

const NAME = 'B';
let call = (who) => {
 console.log('Hello ' + who + '! I am ' + NAME);
}
module.exports = {
 call
}

声明文件 node_modules/b/types/index.d.ts 内容如下:

declare namespace b {
 function call(who: string): void;
}
export = b;

这时,我们修改 src/index.ts :

import a from './a';
a.call('Pwcong');
import b = require('b');
b.call('Pwcong');

命令行执行 tsc 后即可在目录 dist 中生成js代码后执行命令 node ./dist/index.js 也可以得到相应正确的输出。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

vuex里mapState,mapGetters使用详解

vue常用组件使用详解

The above is the detailed content of Detailed explanation of the use of js bundled TypeScript declaration. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor