概述
🌐 Overview
当你有一个基于 MSBuild 的项目并使用 TypeScript,例如 ASP.NET Core 项目时,你可以通过两种方式配置 TypeScript。要么通过 tsconfig.json,要么通过项目设置。
🌐 When you have an MSBuild based project which utilizes TypeScript such as an ASP.NET Core project, you can configure TypeScript in two ways. Either via a tsconfig.json or via the project settings.
使用 tsconfig.json
🌐 Using a tsconfig.json
我们建议在可能的情况下在你的项目中使用 tsconfig.json。要将其添加到现有项目中,请在你的项目中添加一个新项,在现代版本的 Visual Studio 中,这个新项称为“TypeScript JSON 配置文件”。
🌐 We recommend using a tsconfig.json for your project when possible. To add one to an existing project, add a new item to your project which is called a “TypeScript JSON Configuration File” in modern versions of Visual Studio.
新的 tsconfig.json 将被用作 TypeScript 特定构建信息(如文件和配置)的真实来源。你可以在这里了解 TSConfigs 的工作原理,并且这里有一个 全面的参考。
🌐 The new tsconfig.json will then be used as the source of truth for TypeScript-specific build information like files and configuration. You can learn about how TSConfigs works here and there is a comprehensive reference here.
使用项目设置
🌐 Using Project Settings
你也可以在项目的设置中定义 TypeScript 的配置。这可以通过编辑你 .csproj 中的 XML 来定义 PropertyGroups,以描述构建如何工作:
🌐 You can also define the configuration for TypeScript inside you project’s settings. This is done by editing the XML in your .csproj to define PropertyGroups which describe how the build can work:
xml<PropertyGroup><TypeScriptNoEmitOnError>true</TypeScriptNoEmitOnError><TypeScriptNoImplicitReturns>true</TypeScriptNoImplicitReturns></PropertyGroup>
有一系列用于常见 TypeScript 设置的映射,这些设置直接映射到 TypeScript CLI 选项,用于帮助你编写更易理解的项目文件。你可以使用 TSConfig 参考 获取关于每个映射的值和默认值的更多信息。
🌐 There is a series of mappings for common TypeScript settings, these are settings which map directly to TypeScript cli options and are used to help you write a more understandable project file. You can use the TSConfig reference to get more information on what values and defaults are for each mapping.
CLI Mappings
| MSBuild Config Name | TSC Flag | |
|---|---|---|
<TypeScriptAllowJS> |
--allowJs |
|
|
Allow JavaScript files to be a part of your program. Use the | ||
<TypeScriptRemoveComments> |
--removeComments |
|
|
Disable emitting comments. | ||
<TypeScriptNoImplicitAny> |
--noImplicitAny |
|
|
Enable error reporting for expressions and declarations with an implied | ||
<TypeScriptGeneratesDeclarations> |
--declaration |
|
|
Generate .d.ts files from TypeScript and JavaScript files in your project. | ||
<TypeScriptModuleKind> |
--module |
|
|
Specify what module code is generated. | ||
<TypeScriptJSXEmit> |
--jsx |
|
|
Specify what JSX code is generated. | ||
<TypeScriptOutDir> |
--outDir |
|
|
Specify an output folder for all emitted files. | ||
<TypeScriptSourceMap> |
--sourcemap |
|
|
Create source map files for emitted JavaScript files. | ||
<TypeScriptTarget> |
--target |
|
|
Set the JavaScript language version for emitted JavaScript and include compatible library declarations. | ||
<TypeScriptNoResolve> |
--noResolve |
|
|
Disallow | ||
<TypeScriptMapRoot> |
--mapRoot |
|
|
Specify the location where debugger should locate map files instead of generated locations. | ||
<TypeScriptSourceRoot> |
--sourceRoot |
|
|
Specify the root path for debuggers to find the reference source code. | ||
<TypeScriptCharset> |
--charset |
|
|
No longer supported. In early versions, manually set the text encoding for reading files. | ||
<TypeScriptEmitBOM> |
--emitBOM |
|
|
Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. | ||
<TypeScriptNoLib> |
--noLib |
|
|
Disable including any library files, including the default lib.d.ts. | ||
<TypeScriptPreserveConstEnums> |
--preserveConstEnums |
|
|
Disable erasing | ||
<TypeScriptSuppressImplicitAnyIndexErrors> |
--suppressImplicitAnyIndexErrors |
|
|
Suppress | ||
<TypeScriptNoEmitHelpers> |
--noEmitHelpers |
|
|
Disable generating custom helper functions like | ||
<TypeScriptInlineSourceMap> |
--inlineSourceMap |
|
|
Include sourcemap files inside the emitted JavaScript. | ||
<TypeScriptInlineSources> |
--inlineSources |
|
|
Include source code in the sourcemaps inside the emitted JavaScript. | ||
<TypeScriptNewLine> |
--newLine |
|
|
Set the newline character for emitting files. | ||
<TypeScriptIsolatedModules> |
--isolatedModules |
|
|
Ensure that each file can be safely transpiled without relying on other imports. | ||
<TypeScriptEmitDecoratorMetadata> |
--emitDecoratorMetadata |
|
|
Emit design-type metadata for decorated declarations in source files. | ||
<TypeScriptRootDir> |
--rootDir |
|
|
Specify the root folder within your source files. | ||
<TypeScriptExperimentalDecorators> |
--experimentalDecorators |
|
|
Enable experimental support for TC39 stage 2 draft decorators. | ||
<TypeScriptModuleResolution> |
--moduleResolution |
|
|
Specify how TypeScript looks up a file from a given module specifier. | ||
<TypeScriptSuppressExcessPropertyErrors> |
--suppressExcessPropertyErrors |
|
|
Disable reporting of excess property errors during the creation of object literals. | ||
<TypeScriptReactNamespace> |
--reactNamespace |
|
|
Specify the object invoked for | ||
<TypeScriptSkipDefaultLibCheck> |
--skipDefaultLibCheck |
|
|
Skip type checking .d.ts files that are included with TypeScript. | ||
<TypeScriptAllowUnusedLabels> |
--allowUnusedLabels |
|
|
Disable error reporting for unused labels. | ||
<TypeScriptNoImplicitReturns> |
--noImplicitReturns |
|
|
Enable error reporting for codepaths that do not explicitly return in a function. | ||
<TypeScriptNoFallthroughCasesInSwitch> |
--noFallthroughCasesInSwitch |
|
|
Enable error reporting for fallthrough cases in switch statements. | ||
<TypeScriptAllowUnreachableCode> |
--allowUnreachableCode |
|
|
Disable error reporting for unreachable code. | ||
<TypeScriptForceConsistentCasingInFileNames> |
--forceConsistentCasingInFileNames |
|
|
Ensure that casing is correct in imports. | ||
<TypeScriptAllowSyntheticDefaultImports> |
--allowSyntheticDefaultImports |
|
|
Allow 'import x from y' when a module doesn't have a default export. | ||
<TypeScriptNoImplicitUseStrict> |
--noImplicitUseStrict |
|
|
Disable adding 'use strict' directives in emitted JavaScript files. | ||
<TypeScriptLib> |
--lib |
|
|
Specify a set of bundled library declaration files that describe the target runtime environment. | ||
<TypeScriptBaseUrl> |
--baseUrl |
|
|
Specify the base directory to resolve bare specifier module names. | ||
<TypeScriptDeclarationDir> |
--declarationDir |
|
|
Specify the output directory for generated declaration files. | ||
<TypeScriptNoImplicitThis> |
--noImplicitThis |
|
|
Enable error reporting when | ||
<TypeScriptSkipLibCheck> |
--skipLibCheck |
|
|
Skip type checking all .d.ts files. | ||
<TypeScriptStrictNullChecks> |
--strictNullChecks |
|
|
When type checking, take into account | ||
<TypeScriptNoUnusedLocals> |
--noUnusedLocals |
|
|
Enable error reporting when a local variables aren't read. | ||
<TypeScriptNoUnusedParameters> |
--noUnusedParameters |
|
|
Raise an error when a function parameter isn't read | ||
<TypeScriptAlwaysStrict> |
--alwaysStrict |
|
|
Ensure 'use strict' is always emitted. | ||
<TypeScriptImportHelpers> |
--importHelpers |
|
|
Allow importing helper functions from tslib once per project, instead of including them per-file. | ||
<TypeScriptJSXFactory> |
--jsxFactory |
|
|
Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' | ||
<TypeScriptStripInternal> |
--stripInternal |
|
|
Disable emitting declarations that have | ||
<TypeScriptCheckJs> |
--checkJs |
|
|
Enable error reporting in type-checked JavaScript files. | ||
<TypeScriptDownlevelIteration> |
--downlevelIteration |
|
|
Emit more compliant, but verbose and less performant JavaScript for iteration. | ||
<TypeScriptStrict> |
--strict |
|
|
Enable all strict type checking options. | ||
<TypeScriptNoStrictGenericChecks> |
--noStrictGenericChecks |
|
|
Disable strict checking of generic signatures in function types. | ||
<TypeScriptPreserveSymlinks> |
--preserveSymlinks |
|
|
Disable resolving symlinks to their realpath. This correlates to the same flag in node. | ||
<TypeScriptStrictFunctionTypes> |
--strictFunctionTypes |
|
|
When assigning functions, check to ensure parameters and the return values are subtype-compatible. | ||
<TypeScriptStrictPropertyInitialization> |
--strictPropertyInitialization |
|
|
Check for class properties that are declared but not set in the constructor. | ||
<TypeScriptESModuleInterop> |
--esModuleInterop |
|
|
Emit additional JavaScript to ease support for importing CommonJS modules. This enables | ||
<TypeScriptEmitDeclarationOnly> |
--emitDeclarationOnly |
|
|
Only output d.ts files and not JavaScript files. | ||
<TypeScriptKeyofStringsOnly> |
--keyofStringsOnly |
|
|
Make keyof only return strings instead of string, numbers or symbols. Legacy option. | ||
<TypeScriptUseDefineForClassFields> |
--useDefineForClassFields |
|
|
Emit ECMAScript-standard-compliant class fields. | ||
<TypeScriptDeclarationMap> |
--declarationMap |
|
|
Create sourcemaps for d.ts files. | ||
<TypeScriptResolveJsonModule> |
--resolveJsonModule |
|
|
Enable importing .json files | ||
<TypeScriptStrictBindCallApply> |
--strictBindCallApply |
|
|
Check that the arguments for | ||
<TypeScriptNoEmitOnError> |
--noEmitOnError |
|
|
Disable emitting files if any type checking errors are reported. | ||
附加标志
🌐 Additional Flags
由于 MSBuild 系统会将参数直接传递给 TypeScript CLI,因此你可以使用选项 TypeScriptAdditionalFlags 来提供上面未列出的特定标志。
🌐 Because the MSBuild system passes arguments directly to the TypeScript CLI, you can use the option TypeScriptAdditionalFlags to provide specific flags which don’t have a mapping above.
例如,这将打开 noPropertyAccessFromIndexSignature:
🌐 For example, this would turn on noPropertyAccessFromIndexSignature:
xml<TypeScriptAdditionalFlags> $(TypeScriptAdditionalFlags) --noPropertyAccessFromIndexSignature</TypeScriptAdditionalFlags>
调试和发布版本
🌐 Debug and Release Builds
你可以使用 PropertyGroup 条件来定义不同的配置集。例如,一个常见的任务是在生产环境中去除注释和源映射。在此示例中,我们定义了一个调试和发布的属性组,它们具有不同的 TypeScript 配置:
🌐 You can use PropertyGroup conditions to define different sets of configurations. For example, a common task is stripping comments and sourcemaps in production. In this example, we define a debug and release property group which have different TypeScript configurations:
xml<PropertyGroup Condition="'$(Configuration)' == 'Debug'"><TypeScriptRemoveComments>false</TypeScriptRemoveComments><TypeScriptSourceMap>true</TypeScriptSourceMap></PropertyGroup><PropertyGroup Condition="'$(Configuration)' == 'Release'"><TypeScriptRemoveComments>true</TypeScriptRemoveComments><TypeScriptSourceMap>false</TypeScriptSourceMap></PropertyGroup><ImportProject="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets"Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets')" />
ToolsVersion
项目文件中 <TypeScriptToolsVersion>1.7</TypeScriptToolsVersion> 属性的值用于确定要使用的编译器版本(在此示例中为 1.7)。
这允许项目在不同的机器上使用相同的编译器版本进行构建。
🌐 The value of <TypeScriptToolsVersion>1.7</TypeScriptToolsVersion> property in the project file identifies the compiler version to use to build (1.7 in this example).
This allows a project to build against the same versions of the compiler on different machines.
如果未指定 TypeScriptToolsVersion,将使用机器上安装的最新编译器版本进行构建。
🌐 If TypeScriptToolsVersion is not specified, the latest compiler version installed on the machine will be used to build.
使用较新版本 TS 的用户将在首次加载时看到升级项目的提示。
🌐 Users using newer versions of TS, will see a prompt to upgrade their project on first load.
TypeScriptCompileBlocked
如果你使用不同的构建工具来构建项目(例如 gulp、grunt 等),并且使用 Visual Studio 进行开发和调试体验,请在项目中设置 <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>。
这样可以为你提供所有的编辑支持,但在按 F5 时不会进行构建。
🌐 If you are using a different build tool to build your project (e.g. gulp, grunt , etc.) and VS for the development and debugging experience, set <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked> in your project.
This should give you all the editing support, but not the build when you hit F5.
TypeScriptEnableIncrementalMSBuild(TypeScript 4.2 Beta 及更高版本)
🌐 TypeScriptEnableIncrementalMSBuild (TypeScript 4.2 Beta and later)
默认情况下,MSBuild 仅在项目的源文件自上次编译以来已更新时才尝试运行 TypeScript 编译器。但是,如果这种行为导致问题,例如当启用 TypeScript 的 incremental 选项时,请设置 <TypeScriptEnableIncrementalMSBuild>false</TypeScriptEnableIncrementalMSBuild> 以确保每次运行 MSBuild 时都调用 TypeScript 编译器。
🌐 By default, MSBuild will attempt to only run the TypeScript compiler when the project’s source files have been updated since the last compilation.
However, if this behavior is causing issues, such as when TypeScript’s incremental option is enabled, set <TypeScriptEnableIncrementalMSBuild>false</TypeScriptEnableIncrementalMSBuild> to ensure the TypeScript compiler is invoked with every run of MSBuild.