模块化

typescript最主要使用的模块化方案是 ES Module

知识点

  • 在JS中规范声明如何没有 export 的 JS 文件都当作为一个脚本,并非模块
  • 在脚本文件中,变量和类型会被声明在共享的全局作用域,将多个输入文件合并成一个输出文件,或者在 HTML使用多个 <script> 标签加载这些文件

将文件转成模块化

文件加上 export{} 将会被模块处理,此时没有导出任何东西。{}里添加导出的内容即可

内置类型导入导出

TS支持单文件导入导出,只需要加入 type 前缀,表示导入的是一个类型

// type.ts
export type IDType = number 

export interface IFoo = {
  name: string
  age: number
}

// index.ts
import {type IDType,  type IFoo } from './type'
// 写在前面也可,表示都是导入的都是type
import type {IDType, IFoo} from './type'

const id: IDType = 101

const foo: IFoo = {
  name: 'zs',
  age: 19
}

命名空间 namespace

命名空间在TypeScript早期时,称之为内部模块,目的是将一个模块内部再进行作用域的划分,防止一些命名冲突的问题

虽然命名空间没被废弃,但是 ES 模块已经拥有了命名空间的大部分特性,推荐使用 ES 模块

namespace Shapes {
    export namespace Polygons {
        export class Triangle { }
        export class Square { }
    }
}

import polygons = Shapes.Polygons;
let sq = new polygons.Square(); // Same as "new Shapes.Polygons.Square()"

类别的查找

TS中还有另外一种文件.d.ts 用来做类型的声明,称之为类型声明(declaration)

它仅仅用来做类型检测,告知typescript我们有哪些类型

  1. 内置类型声明
  2. 外部定义类型声明
  3. 自己定义类型声明

内置声明的使用

TS自带内置声明,用来声明JS标准化的API,比如funtion, string, dom 等

内置类型声明通常在我们安装typescript的环境中会带有的–查看

可以通过target和lib来决定哪些内置类型声明是可以使用
如,startsWith字符串方法只能从称为ES6的 JS 版本开始使用

查看连接

外部声明的使用

第三方库

通常我们使用第三方库也需要一些类型声明

第三方库有两种类型声明方法

  1. 自带 .d.ts 文件, 比如 axios,导入即可
  2. 通过社区的一个公有库DefinitelyTyped存放类型声明文件
  • 该库的GitHub地址:查看
  • 该库查找声明安装方式的地址:查看
  • 比如我们安装react的类型声明: npm i @types/react --save-dev

自定义声明

  • 情况一:我们使用的第三方库是一个纯的JavaScript库,没有对应的声明文件 比如lodash
  • 情况二:我们给自己的代码中声明一些类型,方便在其他地方直接进行使用

关键词 declare

let name = 'zs'
let age = 18

funtion foo{}

funtion person(name, age){
  this.name = name
  this.age = age
}

// 声明
declare let name: string
declare let age: number

declare function foo(): void

declare class Person {
  name: string
  age: number
}

声明模块

声明模块的语法: `declare module ‘模块名’ {}``
在声明模块的内部,我们可以通过 export 导出对应库的类、函数等

// 比如lodash
declare module 'lodash' {
  export funtion join(args[]: any[]): any[]
}

声明文件

比如在 vue 开发中默认不识别 .vue 文件,使用了 jpg 这类图片文件,默认TS也是不支持的
所以我们也对上面不识别进行声明

// .vue文件
declare module '*.vue' {
  // 导入 vue 组件类型
  import type { DefineComponent } from 'vue'
  const component: DefineComponent
  export default component
}

// .jpg 文件
declare module '*.jpg' {
  const src: string
  export default src
}

命名空间

如果在 index.html 通过CDN 引入 JQuery,可以进行命名空间

declare namespace ${
  funtion ajax(setting: any): void
}

// main.ts 使用
$.ajax({
  url:'url'
  success:(res:any)=>{}
})

tsconfig.json文件

作用

tsconfig.json文件有两个作用:

  1. 作用一(主要的作用):让TypeScript Compiler在编译的时候,知道如何去编译TypeScript代码和进行类型检测
    • 比如是否允许不明确的this选项,是否允许隐式的any类型
    • 将TypeScript代码编译成什么版本的JavaScript代码
  2. 作用二:让编辑器(比如VSCode)可以按照正确的方式识别TypeScript代码
    • 对于哪些语法进行提示、类型错误检测等等

webpack中使用ts-loader进行打包时,也会自动读取tsconfig文件,根据配置编译TypeScript代码

选项

不用记住每一个,查看文档对于每个选项的解释:文档

当我们开发项目的时候,选择TS模板时,tsconfig文件默认都会配置好的

webpack 配置TS环境

  1. 初始化package.json npm init

  2. 下载包

    • webpack npm i webpack webpack-cli webpack-dev-server -D
    • TS解析 npm i ts-loader -D
    • html插件 npm i html-webpack-plugin -D
  3. 配置 webpack

    • 创建 webpack.config.js 文件, 入口文件 src/index.ts、index.html
    const path = require("path")
    const HtmlWeabpckPlugin = require("html-webpack-plugin")
    module.exports = {
      mode: "development",
      entry: "./src/index.ts",
      output: {
      path: path.resolve(__dirname, "./dist"),
      filename: "bundle.js"
    },
    resolve: {
      extensions: [".ts", ".js", ".cjs", ".json"]
    },
    devServer: {},
    module: {
      rules: [
        {
          test: /\.ts$/,
          loader: "ts-loader"
        },
        {
          test: /\.(png|jpe?g|svg|gif)$/,
          type: "asset/resource"
        }
      ]
    },
    plugins: [
      new HtmlWeabpckPlugin({
        template: "./index.html"
      })
     ]
    }
    
  4. 配置tsconfig.json 命令行初始化 tsc --init,或者手动创建写入

     {
    
     "compilerOptions": {
    
       /* Visit https://aka.ms/tsconfig to read more about this file */
    
    
    
       /* Projects */
     
       // "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
     
       // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
     
       // "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */
     
       // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */
     
       // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
     
       // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */
    
    
    
       /* Language and Environment */
     
       // "target": "ES3",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
     
       // "lib": ["DOM"],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
     
       // "jsx": "preserve",                                /* Specify what JSX code is generated. */
     
       // "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
     
       // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
     
       // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
     
       // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
     
       // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
     
       // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
     
       // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
     
       // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
     
       // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */
    
    
    
       /* Modules */
     
       "module": "commonjs",                                /* Specify what module code is generated. */
     
       // "rootDir": "./",                                  /* Specify the root folder within your source files. */
     
       // "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
     
       // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
     
       // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
     
       // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
     
       // "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */
     
       // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
     
       // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
     
       // "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */
     
       // "resolveJsonModule": true,                        /* Enable importing .json files. */
     
       // "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
    
    
    
       /* JavaScript Support */
     
       // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
     
       // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
     
       // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
    
    
    
       /* Emit */
     
       // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
     
       // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
     
       // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
     
       // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
     
       // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
     
       // "outDir": "./",                                   /* Specify an output folder for all emitted files. */
     
       // "removeComments": true,                           /* Disable emitting comments. */
     
       // "noEmit": true,                                   /* Disable emitting files from a compilation. */
     
       // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
     
       // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */
     
       // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
     
       // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
     
       // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
     
       // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
     
       // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
     
       // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
     
       // "newLine": "crlf",                                /* Set the newline character for emitting files. */
     
       // "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
     
       // "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */
     
       // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
     
       // "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */
     
       // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
     
       // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
    
    
    
       /* Interop Constraints */
     
       // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
     
       // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
     
       "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
     
       // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
     
       "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */
    
    
    
       /* Type Checking */
     
       "strict": true,                                      /* Enable all strict type-checking options. */
     
       "noImplicitAny": false,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */
     
       "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */
     
       "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
     
       // "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
     
       // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
     
       "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */
     
       // "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */
     
       // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
     
       // "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */
     
       // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */
     
       // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
     
       // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
     
       // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
     
       // "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */
     
       // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
     
       // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */
     
       // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
     
       // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */
    
    
    
       /* Completeness */
     
       // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
     
       "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
     
     },
     
     // "files": [] 指定哪些ts文件需要进行编译
     
     // "include": ["./src/**/*.ts", "./types/*.d.ts"]
    
    }
    
    
  5. 配置运行脚本, package.json

    "scripts": {
      "serve": "webpack serve",
      "build": "webpack"
    },
    
  6. 使用 npm run serve 运行

TS封装axios

todo…


参考资料

TS中文网

coderwhy前端课程