TypeScript+react+webpack

    技术2022-07-17  64

    因为接下来的项目,需要用到TypeScript,总结一下学习内容

    1、Installing TypeScript

    npm install -g typescript

    2、build ts file

    tsc **.ts

    3、type annotations

    在ts中,必须要定义变量的类型,主要有:

    boolean: let isdone:boolean=false

    number: let num:number =6 / 0xf00d / 0b1010 / 0o744

    string:let s:string='test'

    Array:let list:Array<number>=[1,2,3].

    Tuple:let x:[String,number]=['a',1]

    Enum:enum Color {Red,Green,Blue} let c:Color=Color.Green

    Any:let notSure:any=4  noteSure="test" notSure=false

    void: function fun():void{consolt.log('test')}

    null and undefined:let u:undefined=u:undefined      let n:null=null

    never:

    // Function returning never must have unreachable end point function error(message: string): never { throw new Error(message); } // Inferred return type is never function fail() { return error("Something failed"); } // Function returning never must have unreachable end point function infiniteLoop(): never { while (true) { } }

    Object :represents the non-primitive type, i.e. anything that is not number, string, boolean, bigint, symbol, null, or undefined:

    Type assertions:Type assertions have two forms. One is the “angle-bracket” syntax:

    let someValue: any = "this is a string"; let strLength: number = (<string>someValue).length;

    And the other is the as-syntax:

    let someValue: any = "this is a string"; let strLength: number = (someValue as string).length;

     两种方式都可以:但是如果要是要转换为JSX的话,只能用as

     

    4、How to wire up typescript with react and webpack

    1)新建项目

    mkdir proj cd proj mkdir src cd src mkdir components cd ..

    the strcture like this:

    proj/ ├─ dist/ └─ src/ └─ components/

    webpack 可以自动生成dist文件夹

    2)初始化项目

    npm init -y

    创建package.json

    3)安装依赖

    npm install --save-dev webpack webpack-cli npm install --save react react-dom npm install --save-dev @types/react @types/react-dom //let ts and webpack play well together npm install --save-dev typescript ts-loader source-map-loader

     4)添加typescript配置文件:learn more about tsconfig.json

    { "compilerOptions": { "outDir": "./dist/", "sourceMap": true, "noImplicitAny": true, "module": "commonjs", "target": "es6", "jsx": "react" } }

    5)开始写功能

    create a file named hello.tsx in src/components

    import * as React from "react"; export interface HelloProps { compiler: string; framework: string; } export const Hello = (props: HelloProps) => <h1>Hello from {props.compiler} and {props.framework}!</h1>;

     或者:

    import * as React from "react"; export interface HelloProps { compiler: string; framework: string; } // 'HelloProps' describes the shape of props. // State is never set so we use the '{}' type. export class Hello extends React.Component<HelloProps, {}> { render() { return <h1>Hello from {this.props.compiler} and {this.props.framework}!</h1>; } }

     Then create an index.tsx in src

    import * as React from "react"; import * as ReactDOM from "react-dom"; import { Hello } from "./components/Hello"; ReactDOM.render( <Hello compiler="TypeScript" framework="React" />, document.getElementById("example") );

    create a file at the root of proj named index.html

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Hello React!</title> </head> <body> <div id="example"></div> <!-- Dependencies --> <script src="./node_modules/react/umd/react.development.js"></script> <script src="./node_modules/react-dom/umd/react-dom.development.js"></script> <!-- Main --> <script src="./dist/main.js"></script> </body> </html>

    6)create webpack configuration:webpack.config.js

    module.exports = { mode: "production", // Enable sourcemaps for debugging webpack's output. devtool: "source-map", resolve: { // Add '.ts' and '.tsx' as resolvable extensions. extensions: [".ts", ".tsx"] }, module: { rules: [ { test: /\.ts(x?)$/, exclude: /node_modules/, use: [ { loader: "ts-loader" } ] }, // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. { enforce: "pre", test: /\.js$/, loader: "source-map-loader" } ] }, // When importing a module whose path matches one of the following, just // assume a corresponding global variable exists and use that instead. // This is important because it allows us to avoid bundling all of our // dependencies, which allows browsers to cache those libraries between builds. externals: { "react": "React", "react-dom": "ReactDOM" } };

     

    npx webpack
    Processed: 0.009, SQL: 9