TypeScript 的介绍

TypeScript 是 JavaScript 的一个超集,支持 ECMAScript 6 (ES6)标准。
TypeScript 由微软开发的自由和开源的编程语言。
TypeScript 设计目标是开发大型应用,它可以编译成纯 JavaScript,编译出来的 JavaScript 可以运行在任何浏览器上。

安装 TypeScript

安装:npm install -g typescript
检测安装:tsc -v 或 tsc --version 或者 tsc

手动编译 TS 代码

新建: crj.ts

(()=>{function crjFun(str:string){return "您好" + str;}let a:string = '祖国'console.log(crjFun(a));
})()

编译:命令行执行 tsc crj.ts 后生成 crj.js

(function () {function crjFun(str) {return "您好" + str;}var a = '祖国';console.log(crjFun(a));
})();

测试一:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><script src="crj.js"></script>
</body>
</html>

结果:浏览器控制台打印出 :您好祖国

测试二: node crj.js

结果: 控制台输出 您好祖国

自动编译 TS 代码 【在VScode中】

1). 生成配置文件tsconfig.jsontsc --init
2). 修改tsconfig.json配置"outDir": "./js", "strict": false,  // 不使用严格模式
3). 启动监视任务: 终端 -> 运行任务 -> 监视tsconfig.json

实例

npm init -y  创建了package.json配置文件。
tsc --init 创建了tsconfig.json配置文件。
npm install @types/node --dev-save  模块生成文件问题

终端-->运行生成任务-->tsc:构建--tsconfig.json

node greeter.js

tsconfig.json

tsconfig.json文件是 TypeScript 编译器的配置文件,TypeScript 编译器可以根据它的规则来对代码进行编译。

{"compilerOptions": {/* Visit https://aka.ms/tsconfig.json to read more about this file *//* Projects */// "incremental": true,                              /* Enable incremental compilation */// "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */// "tsBuildInfoFile": "./",                          /* Specify the folder for .tsbuildinfo incremental compilation files. */// "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": "es5",                                     /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */// "lib": [],                                        /* 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. *//* 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. */// "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. */"outDir": "./js",                                  /* 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. *//* 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. */"strict": false,                                      /* Enable all strict type-checking options. */// "noImplicitAny": true,                            /* 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,               /* Type catch clause variables as 'unknown' instead of 'any'. */// "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */// "noUnusedLocals": true,                           /* Enable error reporting when a 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,                 /* Include 'undefined' in index signature results */// "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. */}// 翻译"compilerOptions": {"incremental": true, // TS编译器在第一次编译之后会生成一个存储编译信息的文件,第二次编译会在第一次的基础上进行增量编译,可以提高编译的速度"tsBuildInfoFile": "./buildFile", // 增量编译文件的存储位置"diagnostics": true, // 打印诊断信息 "target": "ES5", // 目标语言的版本"module": "CommonJS", // 生成代码的模板标准"outFile": "./app.js", // 将多个相互依赖的文件生成一个文件,可以用在AMD模块中,即开启时应设置"module": "AMD","lib": ["DOM", "ES2015", "ScriptHost", "ES2019.Array"], // TS需要引用的库,即声明文件,es5 默认引用dom、es5、scripthost,如需要使用es的高级版本特性,通常都需要配置,如es8的数组新特性需要引入"ES2019.Array","allowJS": true, // 允许编译器编译JS,JSX文件"checkJs": true, // 允许在JS文件中报错,通常与allowJS一起使用"outDir": "./dist", // 指定输出目录"rootDir": "./", // 指定输出文件目录(用于输出),用于控制输出目录结构"declaration": true, // 生成声明文件,开启后会自动生成声明文件"declarationDir": "./file", // 指定生成声明文件存放目录"emitDeclarationOnly": true, // 只生成声明文件,而不会生成js文件"sourceMap": true, // 生成目标文件的sourceMap文件"inlineSourceMap": true, // 生成目标文件的inline SourceMap,inline SourceMap会包含在生成的js文件中"declarationMap": true, // 为声明文件生成sourceMap"typeRoots": [], // 声明文件目录,默认时node_modules/@types"types": [], // 加载的声明文件包"removeComments":true, // 删除注释 "noEmit": true, // 不输出文件,即编译后不会生成任何js文件"noEmitOnError": true, // 发送错误时不输出任何文件"noEmitHelpers": true, // 不生成helper函数,减小体积,需要额外安装,常配合importHelpers一起使用"importHelpers": true, // 通过tslib引入helper函数,文件必须是模块"downlevelIteration": true, // 降级遍历器实现,如果目标源是es3/5,那么遍历器会有降级的实现"strict": true, // 开启所有严格的类型检查"jsx": "preserve", // 指定 jsx 格式"alwaysStrict": true, // 在代码中注入'use strict'"noImplicitAny": true, // 不允许隐式的any类型"strictNullChecks": true, // 不允许把null、undefined赋值给其他类型的变量"strictFunctionTypes": true, // 不允许函数参数双向协变"strictPropertyInitialization": true, // 类的实例属性必须初始化"strictBindCallApply": true, // 严格的bind/call/apply检查"noImplicitThis": true, // 不允许this有隐式的any类型"noUnusedLocals": true, // 检查只声明、未使用的局部变量(只提示不报错)"noUnusedParameters": true, // 检查未使用的函数参数(只提示不报错)"noFallthroughCasesInSwitch": true, // 防止switch语句贯穿(即如果没有break语句后面不会执行)"noImplicitReturns": true, //每个分支都会有返回值"esModuleInterop": true, // 允许export=导出,由import from 导入"allowUmdGlobalAccess": true, // 允许在模块中全局变量的方式访问umd模块"moduleResolution": "node", // 模块解析策略,ts默认用node的解析策略,即相对的方式导入"baseUrl": "./", // 解析非相对模块的基地址,默认是当前目录"paths": { // 路径映射,相对于baseUrl// 如使用jq时不想使用默认版本,而需要手动指定版本,可进行如下配置"jquery": ["node_modules/jquery/dist/jquery.min.js"]},"rootDirs": ["src","out"], // 将多个目录放在一个虚拟目录下,用于运行时,即编译后引入文件的位置可能发生变化,这也设置可以虚拟src和out在同一个目录下,不用再去改变路径也不会报错"listEmittedFiles": true, // 打印输出文件"listFiles": true// 打印编译的文件(包括引用的声明文件)}
}

根选项
include:指定被编译文件所在的目录。
exclude:指定不需要被编译的目录。
extends:指定要继承的配置文件。
files:指定被编译的文件。
references:项目引用,是 TS 3.0 中的一项新功能,它允许将 TS 程序组织成更小的部分。
以上:使用小技巧:在填写路径时 ** 表示任意目录, * 表示任意文件。
compilerOptions 定义项目的运行时期望、JavaScript 的发出方式和位置以及与现有 JavaScript 代码的集成级别。

项目选项
incremental:是否启用增量编译,指再次编译时只编译增加的内容,默认:false。
target:指定ts编译成ES的版本。
module:指定编译后代码使用的模块化规范。
lib:指定项目运行时使用的库。
outDir:指定编译后文件所在目录。
outFile:将代码编译合并成一个文件,默认将所有全局作用域中的代码合并成一个文件。
rootDir:指定输入文件的根目录,默认情况下当前的项目目录为根目录。
allowJs:是否对js文件进行编译,默认:false。
checkJs:是否检查js代码是否符合语法规范,当使用checkJs,必须使用allowJs,默认:false。
removeComments:是否移除注释,默认:false
noEmit:不生成编译后的文件,默认:false。
jsx:指定JSX代码生成用于的开发环境。
plugins:在编辑器中运行的语言服务插件列表。
declaration:是否生成相应的 .d.ts 声明文件,默认:false。
declarationMap:是否为每个对应的 .d.ts 文件生成一个 Map 文件,使用该功能时,需要declaration或composite配合一起使用,默认:false。
sourceMap:是否生成相应的Map映射的文件,默认:false。
composite:是否开启项目编译,开启该功能,将会生成被编译文件所在的目录,同时开启declaration、declarationMap和incremental,默认:false。
tsBuildInfoFile:指定增量编译信息文件的位置,使用该功能时,必须开启incremental选项。
importHelpers:是否将辅助函数从 tslib 模块导入,默认:false。
downlevelIteration:是否用于转换为旧版本的 JS 提供可迭代对象的全面支持,默认:false。
isolatedModules:是否将每个文件转换为单独的模块,默认:false。

严格检查
strict:是否启动所有严格检查的总开关,默认:false,启动后将开启所有的严格检查选项。
alwaysStrict:是否以严格模式解析,并为每个源文件发出"use strict",默认:false。
noImplicitAny:是否禁止隐式的any类型,默认:false。
noImplicitThis:是否禁止不明确类型的this,默认:false。
strictNullChecks:是否启用严格的空检查,默认:false。
strictBindCallApply:是否在函数上启用严格的’bind’, 'call’和’apply’方法,默认:false。
strictFunctionTypes:是否启用对函数类型的严格检查,默认:false。
strictPropertyInitialization:是否启用严格检查类的属性初始化,默认:false。

模块解析选项
moduleResolution:指定模块解析策略,node或classic
baseUrl:用于解析非绝对模块名的基本目录,相对模块不受影响。
paths:用于设置模块名称基于baseUrl的路径映射关系。
rootDirs:将多个目录放在一个虚拟目录下,运行编译后文件引入的位置发生改变,也不会报错。
typeRoots:指定声明文件或文件夹的路径列表
types:用来指定需要包含的模块,并将其包含在全局范围内。
allowSyntheticDefaultImports:是否允许从没有默认导出的模块中默认导入,默认:false。
esModuleInterop:是否通过为所有导入模块创建命名空间对象,允许CommonJS和ES模块之间的互操作性,开启改选项时,也自动开启allowSyntheticDefaultImports选项,默认:false。
preserveSymlinks:是否不解析符号链接的真实路径,这是为了在 Node.js 中反映相同的标志,默认:false。
allowUmdGlobalAccess:允许您从模块文件内部访问作为全局变量的 UMD 导出,如果不使用该选项,从 UMD 模块导出需要一个导入声明,默认:false。

Map选项
sourceRoot:指定调试器应定位 TypeScript 文件而不是相对源位置的位置。
mapRoot:指定调试器定位Map文件的位置,而不是生成的位置。
inlineSourceMap:是否将Map文件内容嵌套到 JS 文件中,这会导致 JS 文件变大,但在某些情况下会很方便,默认:false。
inlineSources:是否将 .ts 文件的原始内容作为嵌入字符串包含在 .map 文件中,默认:false。

附加检查
noUnusedLocals:是否检查未使用的局部变量,默认:false。
noUnusedParameters:是否检查未使用的参数,默认:false。
noImplicitReturns:检查函数是否不含有隐式返回值,默认:false。
noImplicitOverride:是否检查子类继承自基类时,其重载的函数命名与基类的函数不同步问题,默认:false。
noFallthroughCasesInSwitch:检查switch中是否含有case没有使用break跳出,默认:false。
noUncheckedIndexedAccess:是否通过索引签名来描述对象上有未知键但已知值的对象,默认:false。
noPropertyAccessFromIndexSignature:是否通过" . “(obj.key) 语法访问字段和"索引”( obj[“key”]), 以及在类型中声明属性的方式之间的一致性,默认:false。

实验选项
experimentalDecorators:是否启用对装饰器的实验性支持,装饰器是一种语言特性,还没有完全被 JavaScript 规范批准,默认:false。
emitDecoratorMetadata:为装饰器启用对发出类型元数据的实验性支持,默认:false。

高级选项
allowUnreachableCode:是否允许无法访问的代码(undefined / true / false),默认:undefined。
undefined:向编辑提供建议作为警告。
true:未使用的标签被忽略。
false:引发有关未使用标签的编译器错误。
allowUnusedLabels:是否允许未使用的标签(undefined / true / false),默认:undefined。
undefined:向编辑提供建议作为警告。
true:未使用的标签被忽略。
false:引发有关未使用标签的编译器错误。
assumeChangesOnlyAffectDirectDependencies是否避免重新检查/重建所有真正可能受影响的文件,而只会重新检查/重建已更改的文件以及直接导入它们的文件,默认:false。
charset:字符集(已弃用),默认:utf8
declarationDir:提供一种方法来配置发出声明文件的根目录。
diagnostics:用于输出用于调试的诊断信息
disableReferencedProjectLoad:是否禁用所有可用项目加载到内存中,默认:false。
disableSizeLimit:为了避免在处理非常大的 JS 项目时可能出现的内存膨胀问题,TS 将分配的内存量有一个上限,默认:false。
disableSolutionSearching:在编辑器中搜索查找所有引用或跳转到定义等功能时,禁止包含复合项目,默认:false。
disableSourceOfProjectReferenceRedirect:是否禁用项目引用源重定向,默认:false。
emitBOM:控制TypeScript在写输出文件时是否发出字节顺序标记(BOM),默认:false。
emitDeclarationOnly:是否只发出.d.ts 文件,不发出.js 文件,使用该选项时,需要配合 declaration 或 composite 一起使用,默认:false。
explainFiles:解释文件,此选项用于调试文件如何成为编译的一部分,默认:false。
extendedDiagnostics:是否查看 TS 在编译时花费的时间,默认:false。
forceConsistentCasingInFileNames:是否区分文件系统大小写规则,默认:false。
generateCpuProfile:在编译阶段让 TS 发出 CPU 配置文件,只能通过终端或 CLI 调用 --generateCpuProfile tsc-output.cpuprofile 。
importsNotUsedAsValues:此标志控制如何 import 工作方式,有 3 个不同的选项:remove、preserve 和 error 。
jsxFactory:当使用经典的JSX运行时编译JSX元素时,更改.js文件中调用的函数,默认:React.createElement 。
jsxFragmentFactory:指定 JSX 片段工厂函数在指定了 jsxFactory 编译器选项的情况下针对 react JSX 发出时使用。
jsxImportSource:当在TS 4.1中使用 jsx 作为 react-jsx 或 react-jsxdev 时,声明用于导入jsx和jsxs工厂函数的模块说明符。
keyofStringsOnly:当应用具有字符串索引签名的类型时,此标志将类型操作符的键值更改为返回 string 而不是string | number,已弃用,默认:false。
listEmittedFiles:是否将编译部分生成的文件的名称打印到终端,默认:false。
listFiles:是否打印编译文件部分的名称,默认:false。
maxNodeModuleJsDepth:在node_modules下搜索并加载JavaScript文件的最大依赖深度,默认:0 。
newLine:指定发出文件时要使用的换行规则,CRLF (dos) 或 LF (unix)。
noEmitHelpers:是否使用全局作用域助手函数提供实现,并完全关闭助手函数的发出,而不是使用 importhelper 来导入助手函数,默认:false。
noEmitOnError:有错误时不进行编译,默认:false。
noErrorTruncation:是否禁止截断错误消息,已弃用,默认:false。
noImplicitUseStrict:是否禁止无隐式严格模式,默认:false。
noLib:是否禁止自动包含任何库文件,默认:false。
noResolve:是否禁用析后的文件添加到程序中;默认情况下,TS 会检查 import 和 reference 指令的初始文件集,并将这些解析后的文件添加到你的程序中,默认:false。
noStrictGenericChecks:是否禁用严格的泛型检查,默认:false。
out:该选项以不可预测或一致的方式计算最终文件位置,已弃用,
preserveConstEnums:是否禁止删除枚举常量生成代码中的声明,默认:false。
reactNamespace:React命名空间,使用 jsxFactory 来代替。
resolveJsonModule:是否解析 JSON 模块,默认:false。
skipDefaultLibCheck:是否跳过默认库声明文件的类型检查,默认:false。
skipLibCheck:是否跳过声明文件的类型检查,这可以在编译期间以牺牲类型系统准确性为代价来节省时间,默认:false。
stripInternal:是否禁止 JSDoc 注释中带有@internal注释的代码发出声明,默认:false。
suppressExcessPropertyErrors:是否禁用报告过多的属性错误,默认:false。
suppressImplicitAnyIndexErrors:是否抑制隐式any索引的错误,默认:false。
traceResolution:当尝试调试未包含模块的原因时。启用该选项让 TypeScript 打印有关每个处理文件的解析过程的信息,默认:false。
useDefineForClassFields:此标志用作迁移到即将推出的类字段标准版本的一部分,默认:false。

命令行
preserveWatchOutput:是否在监视模式下保留过时的控制台输出,而不是每次发生更改时都清除屏幕,默认:false。
pretty:是否使用颜色对上下文错误和消息进行样式化,默认:true。

watchOptions 配置 TypeScript 的 --watch工作方式。
监视选项
watchFile:监视单个文件的策略,默认:useFsEvents
fixedPollingInterval:以固定时间间隔每秒多次检查每个文件的更改。
priorityPollingInterval:每秒多次检查每个文件的更改,但使用启发式方法检查某些类型的文件的频率低于其他文件。
dynamicPriorityPolling:使用动态队列,其中不经常修改的文件将不那么频繁地检查。
useFsEvents:尝试使用操作系统/文件系统的本机事件进行文件更改。
useFsEventsOnParentDirectory:尝试使用操作系统/文件系统的本机事件来监听文件父目录的变化。
watchDirectory:在缺乏递归文件监视功能的系统下如何监视整个目录树的策略,默认:useFsEvents
fixedPollingInterval:以固定时间间隔每秒多次检查每个目录的变化。
dynamicPriorityPolling:使用动态队列,其中不经常修改的目录将不那么频繁地检查。
useFsEvents:尝试使用操作系统/文件系统的本机事件进行目录更改。
fallbackPolling:使用文件系统事件时,此选项指定当系统用完本机文件观察器和/或不支持本机文件观察器时使用的轮询策略,默认:dynamicPriorityPolling
fixedPollingInterval:以固定时间间隔每秒多次检查每个文件的更改。
priorityPollingInterval:每秒多次检查每个文件的更改,但使用启发式方法检查某些类型的文件的频率低于其他文件。
dynamicPriorityPolling:使用动态队列,其中不经常修改的文件将不那么频繁地检查。
synchronousWatchDirectory:禁用对目录的延迟监视。
synchronousWatchDirectory:在本机不支持递归观看的平台上同步调用回调,并更新目录观察者的状态,默认:false。
excludeDirectories:使用排除目录来大幅减少 --watch 期间被监视的文件数量.
excludeFiles:使用excludeFiles从被监视的文件中删除一组特定的文件。

typeAcquisition 类型获取仅对 JavaScript 项目很重要。

  1. 类型获取
    enable:提供在 JavaScript 项目中禁用类型获取的配置,默认:false。
    include:使用 include 来指定应从绝对类型中使用哪些类型。
    exclude:提供用于禁用 JavaScript 项目中某个模块的类型获取的配置
    disableFilenameBasedTypeAcquisition:是否禁用基于文件名的类型获取,TypeScript 的类型获取可以根据项目中的文件名推断应该添加哪些类型,默认:false。

使用webpack打包TS

下载依赖

npm init -y  // 创建了package.json配置文件。
tsc --init  // 创建了tsconfig.json配置文件。npm install -D typescript webpack@4.41.5 webpack-cli@3.3.10
webpack-dev-server@3.10.2
html-webpack-plugin clean-webpack-plugin ts-loader cross-envyarn add -D typescript
yarn add -D webpack@4.41.5 webpack-cli@3.3.10
yarn add -D webpack-dev-server@3.10.2
yarn add -D html-webpack-plugin clean-webpack-plugin
yarn add -D ts-loader
yarn add -D cross-env

入口JS: src/main.ts

document.write('Hello Webpack TS!')

index页面: public/index.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>webpack & TS</title>
</head>
<body>
</body>
</html>

build/webpack.config.js

const {CleanWebpackPlugin} = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')const isProd = process.env.NODE_ENV === 'production' // 是否生产环境function resolve (dir) {return path.resolve(__dirname, '..', dir)
}module.exports = {mode: isProd ? 'production' : 'development',entry: {app: './src/main.ts'},output: {path: resolve('dist'),filename: '[name].[contenthash:8].js'},module: {rules: [{test: /\.tsx?$/,use: 'ts-loader',include: [resolve('src')]}]},plugins: [new CleanWebpackPlugin({}),new HtmlWebpackPlugin({template: './public/index.html'})],resolve: {extensions: ['.ts', '.tsx', '.js']},devtool: isProd ? 'cheap-module-source-map' : 'cheap-module-eval-source-map',devServer: {host: 'localhost', // 主机名stats: 'errors-only', // 打包日志输出输出错误信息port: 8081,open: true},
}

配置打包命令

"dev": "cross-env NODE_ENV=development webpack-dev-server --config build/webpack.config.js",
"build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"

运行与打包

npm run dev
npm run build
or
yarn dev
yarn build

TypeScript 简单使用相关推荐

  1. 设计模式-创建型模式-工厂模式(工厂三兄弟) TypeScript

    设计模式-创建型模式-工厂模式(工厂三兄弟) TypeScript 简单工厂模式 定义一个接口,三个具体类.然后书写如下,通过选择,生产出相应的对象 // 定义Shape接口 interface Sh ...

  2. TypeScript+vue使用与迁移经验总结

    源宝导读:ERP平台的前端底层使用了Vue作为组件的基础架构,而使用了TypeScript语言进行组件的封装与开发.本文将简要介绍平台在使用TypeScript和Vue框架进行老功能重构时的经验总结. ...

  3. Typescript 史上最强学习入门文章 ( 2w 字)

    前言 这篇文章参考了很多文章以及看了一些ts视频,然后把基础的知识点全部总结了一下.感觉比掘金上的所有typescript入门的热门文章都要详细 ,因为那些热门文章我全部都参考了,内容基本都包含了.这 ...

  4. 2021 typescript史上最强学习入门文章(4w字)

    前言 这篇文章出自掘金作者:Jimmy_kiwi 本来自己以前是不喜欢ts的,因为它有一定的学习成本,代码量增加,代码复杂度增加等.后来慢慢觉得,ts的静态检查使得开发者提前发现错误,在前端工程化开发 ...

  5. TypeScript设计模式之策略、模板方法

    看看用TypeScript怎样实现常见的设计模式,顺便复习一下. 学模式最重要的不是记UML,而是知道什么模式可以解决什么样的问题,在做项目时碰到问题可以想到用哪个模式可以解决,UML忘了可以查,思想 ...

  6. 《Javscript实用教程》

    图书购买地址:<Javscript实用教程> 目录 Javascript实用教程... 1 目录... 2 第 1 部分... 12 ◄ Javascript基础 ►. 12 第 1 章. ...

  7. 网页3D之babylon.js

    最近公司有虚拟仿真方面的想法,所以做了一些网页3D方面的研究,以及代码,这里记录一下 框架选择 之前用过threejs,所以一开始考虑用threejs做,但是之前用threejs的时候碰到过一个问题: ...

  8. 超简单的react和typescript和引入scss项目搭建流程

    1.首先我们先创建一个react项目,react官网也有react项目搭建的命令 npx create-react-app my-app cd my-app 2.安装我们项目需要的样式依赖,这个项目我 ...

  9. c# typescript_在任何IDE中从C#,Java或Python代码获取TypeScript接口的简单方法

    c# typescript by Leonardo Carreiro 莱昂纳多·卡雷罗(Leonardo Carreiro) 在任何IDE中从C#,Java或Python代码获取TypeScript接 ...

  10. 简单探讨JavaScript 与 TypeScript之间的联系

    这篇文章主要介绍了 JavaScript 与 TypeScript之间的联系,JavaScript,也称为 JS,是一种符合 ECMAScript 规范的编程语言.这是一个高级别的.通常是即时编译的. ...

最新文章

  1. 关于Object.create()与原型链的面试题?
  2. java arraylist comparable_Java 两种ArrayList集合自定义对象属性排序,Comparator接口 或 Comparable接口...
  3. Linux 相关发音
  4. 总结了下自己的几个典型行为
  5. 产品经理如果有捷径,那可能是多读书
  6. java并发:原子类之AtomicLong
  7. 【AI】机器学习博士自救指南(严肃者慎入)
  8. java rhino 运行 js_java 脚本引擎Rhino执行js代码和文件
  9. azure云数据库_在Azure SQL数据库中保护数据的五种方法
  10. 关于.NET中socket中的异步套接字的研究二
  11. python中读取文本文件_Python三种读取txt文件方式
  12. CAD中怎么配置灭火器?
  13. 面试中问到fiddler的那些问题
  14. Arduino -uno 核心板 之中级系列3 QAU04生日快乐歌实验
  15. PyTorch基础(六)-- optim模块
  16. Android常用浏览器,常用六款经典Android平台浏览器推荐
  17. linux的man命令功能,Linux中的MAN命令
  18. 【风马一族_SQL Server】
  19. [漏洞分析] CVE-2022-0995 watch_queue 1bit “溢出“内核提权
  20. 超声波测距模块HC-SR04详解(基于51单片机)

热门文章

  1. 包装严重的IT行业,作为面试官,我是如何甄别应聘者的包装程度!
  2. 怎么快速修改图片的像素?
  3. groovy环境安装
  4. python 网络设备巡检_Python自动巡检H3C交换机实现过程解析
  5. win7系统怎么进行网络重置?
  6. EBS 12.1.3 应用打补丁操作及问题处理
  7. Linux必会100个命令(三十六)gzip
  8. 手机图片转换成文字怎么办
  9. python复合赋值语句语法_复合结构的赋值语句理解
  10. C/C++ 银行账户管理系统