This is the 25th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Examples of TypeScript

The content of this article: module.Copy the code

TypeScript follows the ES6 module concept. Modules execute in their own scope, and variables, functions, classes, and so on defined in a module are not visible outside the module unless we explicitly export them using, for example, export. Then use import and other forms to import.

Export declaration

Any declarations in a module can be exported using the export keyword.

/ / 1
export const baseURL= 'https://www.xxx.com/';
Copy the code

Export a variable

/ / 2
export class Mask {... }Copy the code

Exporting a class

/ / 3
export function fn(a, b) {
    return a + b;
}
Copy the code

Export a function

/ / 4
export interface User {
    name: string
    age: number
}
Copy the code

Exporting an interface

Import module content

/ / case 5
import { baseURL } from './test16'
console.log(baseURL);
Copy the code

Use the import keyword to import exports from other modules. Example 5 imports a baseURL variable.

rename

Rename the exported content using the as keyword as follows:

/ / case 6
const baseURL= 'https://www.xxx.com/';
export {
     baseURL as url
}
Copy the code

You can also rename the imported content using the as keyword as follows:

/ / case 7
import { baseURL as url } from './test16'
console.log(url);
Copy the code

The default is derived

The contents of the module marked with the default keyword represent the default export. Note: a module can only have one default export.

case8
export default function fn(a, b) {
    return a + b;
}
Copy the code

Note: The name of the default exported class or function can be omitted.

The default export can also be a value, as follows:

/ / 9
export default "https://www.xxx.com/";
Copy the code

Modules and namespaces

One of the obvious problems with organizing code through namespaces is that you can’t quickly know where variables are coming from.

Here we rewrite TypeScript examples using modules as a code organization.

/ / 10
// component.ts

export class Mask {
    // todo
}
export class Content {
    // todo
}

// demo.ts
import { Mask, Content} from './component'

export class Create {
    constructor() {
        new Mask();
        newContent(); }}Copy the code

Import is used here to break up and combine modules. In this case, it will default to ADM standard code after packaging. Since ADM standard code cannot run directly on the browser, it needs to introduce additional require.js library to support, or use module packers such as Webpack.

Finish this! If this article helps you at all, please give it a thumbs up.