typescript

Introduction to the

It can be thought of as a superset of JS, adding variable type detection (JS is a weakly typed language), while compatible with all JS syntax.

Environment set up

  1. Install nodejs
  2. sodu npm i -g typescript
  3. Create a ts file app.ts, open the command line and type TSC app.ts

type

Reference to the instance

let a: number; // Number is lowercase
a = 1

Ts can automatically type check variables if they are declared and assigned simultaneously
// There is a bit of a problem with variable declaration assignment, which is mainly used for function parameter verification
let c = false // let c: number = false
c = true
// c = 123

function sum(a:number, b:number) :number {
    return a + b
}

sum(1.2)
Sum (1, '2') // pass a string argument
// sum(1, 2, 3
Copy the code
// Declare directly with literals
let a1: 10;
a1 = 10
// a1 = 12

/ / | can be used to connect multiple types (combined type)
let b1: 'male' | 'female'
b1 = 'male'
b1 = 'female'
// b1 = ''  

// This is a good example
let c1: boolean | string;
c1 = false
c1 = 's'
// c1 = 1


// any Disables TS verification
let d1: any;
// let d1; // Let d1: any
d1 = 1
d1 = '1'

// unknow indicates the unknown type
let e1: unknown;
e1 = 1
e1 = '2'

// The difference between any and unknow
// d1 is of type any and can be assigned to any variable;
// Unknow is a type-safe any that cannot be assigned directly to other variables
let s1: string
s1 = d1
// s1 = e1 // 
if (typeof e1 == 'string') {
    s1 = e1
}

// Type assertion; Tell the compiler that the actual type of the variable E1 is a string to avoid red errors
// The effect is the same
s1 = e1 as string
s1 = <string>e1

// No value, or undefined
function fn() :void {}// There is no return value
function fn2() :never {
    throw new Error('error')}function fn3() :object {
    return null
}
Copy the code
// Since everything is object, this is not meaningful
let a3: object
a3 = {}
a3 = function () {}let b3: { name: string, age? :number } / /? On behalf of the optional
b3 = { name: 'frank'.age: 24 }
b3 = { name: 'coco' }


// [propName: string]: any Property of any type
let c3: { name: string, [propName: string] :any }
c3 = {name: 'frank'.prop1: '1'.prop2: false}

// Type declaration of function structure
let d3: (a: number, b: number) = > number
d3 = function (n1, n2) {
    return n1 + n2
}

// String [] represents an array of strings
let e3: string[]
/ / or
let f3: Array<number>
f3 = [1.2]

// tuple: array of fixed length
let h3: [string.string]
h3 = ['1'.'1']

/ / the enumeration enum
enum Gender {
    Male = 0,
    Female = 1
}

let i3: { name: string.gender: Gender }
i3 = { name: 'frank'.gender: Gender.Male }
console.log(i3.gender == Gender.Male)

// & indicates the relationship between and
// indicates that the js must satisfy both constraints
let j3: { name: string} and {age: number }
j3 = { name: 'frank'.age: 24 }

// Alias of the type
type myType = 1 | 2 | 3 | 4
let k3: myType
let l3: myType
Copy the code

Compiler options

The tsconfig.json file is generated by input instructions from the command line

tsc --init
Copy the code

Listen to the directory under the TS file changes, you can enter instructions

tsc -w
Copy the code

Some common configuration options

  1. include / exclude

Indicates which TS files are compiled and which are not. Exclude does not need to be set actively and has a default value

{
  // ** indicates any directory * indicates any path
  "include": [
    "./src/**/*" // any file and any path in the SRC directory].// Indicates the file directory that does not need to be compiled. The default value exists
  // Default: ['node_modules', 'bower_components', 'jSPM_packages ']
  "exclude": [
    "./src/error/**/*" // SRC /error directory any path or file, do not compile]}Copy the code
  1. CompilerOptions compilerOptions

List some of the more common options

{
    "compilerOptions": {
        // Specify the es version to which ts is compiled
        "target": "es2015".// Specify the modularity specification to use
        "module": "es2015".// Specify the library to use in the project
        "libs": [].// Whether to compile js. Default is false
        "allowJs": true.// Check whether the js code conforms to the specification
        "checkJs": true.// Whether to remove comments at compile time
        "removeComments": true.// Execute only the compilation process, do not generate the compiled file; Generally used to test whether there is a problem with compilation, basic use
        "noEmit": true.// If there is an error during compilation, the compiled file will not be generated
        "noEmitOnError": true.// outDir specifies the directory where the compiled file resides
        "outDir": "./dist".// Merge global-scoped code into the same file
        "outFile": "./dist/app.js".// All strictly checked master switches, if true, are true for the rest. You can set false for each item separately
        "strict": true.// Sets whether compiled code is in strict mode. The default is false
        "alwaysStrict": true.// Implicit this cannot occur
        "noImplicitThis": true.// Implicit any cannot appear. Default is false
        "noImplicitAny": true.// Check strictly for null values
        "strictNullChecks": true.// This feels like a nice attribute to use}}Copy the code

I don’t know about the other options, but most of them don’t remember emmmm

let dom1 = document.getElementById('box')

dom1.addEventListener('click'.() = >{})// Dom1 may be null


// Three ways to avoid potential errors
dom1 && dom1.addEventListener('click'.() = >{})if(dom1 ! =null) {
    dom1.addEventListener('click'.() = >{}) } dom1? .addEventListener('click'.() = > {})

Copy the code

Webpack configuration options

Initial configuration

  1. Select a directory, open terminal, and enter
npm init -y 
Copy the code

Create a package.json file to initialize the project

  1. According to relevant modules
cnpm i -D webpack webpack-cli typescript ts-loader
Copy the code
  1. Add the webpack.config.js file for related configuration

See the code

const path = require('path')

module.exports = {
    mode: 'production'.// development production
    entry: './src/index.ts'.// Import file
    output: {
        path: path.resolve(__dirname, 'dtst'), // Export directory
        filename: 'bundle.js' // Export file
    },
    module: {
        rules: [{test: /\.ts$/,
                use: ['ts-loader'].// Use ts-loader for ts files
                exclude: /node_modules/ // Skip node_modules}]}}Copy the code
  1. Add instructions to package.json file
{
  "scripts": {
    "build": "webpack"."start": "webpack serve --open"}},Copy the code

Enter the NPM run build directive and you can see that the dist/bundle.js file is automatically created. Success!

Introducing several plug-ins

  1. Create HTML files automatically using the HTML-webpack-plugin

  2. Use webpack-dev-server plug-in to automatically create local services and provide heating loading function;

Fill the package.json file with instructions

{
  "scripts": {
    "start": "webpack serve --open"}},Copy the code
  1. Use the clean-webpack-plugin to clean up the DIST each time the packaging instruction is executed

  2. SRC folder, ts files directly into each other, webpack error, to specify reference module

module.exports = {
    resolve: {
        extensions: ['.ts'.'.js']}}Copy the code

With reference to

const path = require('path')
const HWP = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

module.exports = {
    plugins: [
        new CleanWebpackPlugin(),
        new HWP({
            template: './src/index.html'}),].// Setting the reference module to reference ts directly will cause an error
    resolve: {
        extensions: ['.ts'.'.js']}}Copy the code

To be continued