【HarmonyOS NEXT鸿蒙系统应用开发TypeScript(TS)开发基础教程】-第27课时-TypeScript 项目配置详细介绍

TypeScript tsconfig.json

概述

如果一个目录下存在一个tsconfig.json文件,那么它意味着这个目录是TypeScript项目的根目录。tsconfig.json文件中指定了用来编译这个项目的根文件和编译选项。 一个项目可以通过以下方式之一来编译:

使用tsconfig.json

  • 不带任何输入文件的情况下调用tsc,编译器会从当前目录开始去查找tsconfig.json文件,逐级向上搜索父目录。
  • 不带任何输入文件的情况下调用tsc,且使用命令行参数--project(或-p)指定一个包含tsconfig.json文件的目录。

当命令行上指定了输入文件时,tsconfig.json文件会被忽略。

示例

tsconfig.json示例文件:

  • 使用"files"属性
{
    "compilerOptions": {
        "module": "commonjs",
        "noImplicitAny": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "outFile": "../../built/local/tsc.js",
        "sourceMap": true
    },
    "files": [
        "core.ts",
        "sys.ts",
        "types.ts",
        "scanner.ts",
        "parser.ts",
        "utilities.ts",
        "binder.ts",
        "checker.ts",
        "emitter.ts",
        "program.ts",
        "commandLineParser.ts",
        "tsc.ts",
        "diagnosticInformationMap.generated.ts"
    ]
}
  • 使用"include""exclude"属性

    {
        "compilerOptions": {
            "module": "commonjs",
            "noImplicitAny": true,
            "removeComments": true,
            "preserveConstEnums": true,
            "outFile": "../../built/local/tsc.js",
            "sourceMap": true
        },
        "include": [
            "src/**/*"
        ],
        "exclude": [
            "node_modules",
            "**/*.spec.ts"
        ]
    }
    

细节

"compilerOptions"可以被忽略,这时编译器会使用默认值。在这里查看完整的[编译器选项](./Compiler Options.md)列表。

"files"指定一个包含相对或绝对文件路径的列表。 "include""exclude"属性指定一个文件glob匹配模式列表。 支持的glob通配符有:

  • * 匹配0或多个字符(不包括目录分隔符)
  • ? 匹配一个任意字符(不包括目录分隔符)
  • **/ 递归匹配任意子目录

如果一个glob模式里的某部分只包含*.*,那么仅有支持的文件扩展名类型被包含在内(比如默认.ts.tsx,和.d.ts, 如果allowJs设置能true还包含.js.jsx)。

如果"files""include"都没有被指定,编译器默认包含当前目录和子目录下所有的TypeScript文件(.ts,.d.ts 和 .tsx),排除在"exclude"里指定的文件。JS文件(.js.jsx)也被包含进来如果allowJs被设置成true。 如果指定了 "files""include",编译器会将它们结合一并包含进来。 使用 "outDir"指定的目录下的文件永远会被编译器排除,除非你明确地使用"files"将其包含进来(这时就算用exclude指定也没用)。

使用"include"引入的文件可以使用"exclude"属性过滤。 然而,通过 "files"属性明确指定的文件却总是会被包含在内,不管"exclude"如何设置。 如果没有特殊指定, "exclude"默认情况下会排除node_modulesbower_components,和jspm_packages目录。

任何被"files"或"include"指定的文件所引用的文件也会被包含进来。A.ts引用了B.ts,因此B.ts不能被排除,除非引用它的A.ts"exclude"`列表中。

tsconfig.json文件可以是个空文件,那么所有默认的文件(如上面所述)都会以默认配置选项编译。

在命令行上指定的编译选项会覆盖在tsconfig.json文件里的相应选项。

compileOnSave

在最顶层设置compileOnSave标记,可以让IDE在保存文件的时候根据tsconfig.json重新生成文件。

{
    "compileOnSave": true,
    "compilerOptions": {
        "noImplicitAny" : true
    }
}

要想支持这个特性需要Visual Studio 2015, TypeScript1.8.4以上并且安装atom-typescript插件。

模式

到这里查看模式: http://json.schemastore.org/tsconfig.

TypeScript 编译选项

选项类型默认值描述
--allowJsbooleantrue允许编译javascript文件。
--allowSyntheticDefaultImportsbooleanmodule === "system"允许从没有设置默认导出的模块中默认导入。这并不影响代码的显示,仅为了类型检查。
--allowUnreachableCodebooleanfalse不报告执行不到的代码错误。
--allowUnusedLabelsbooleanfalse不报告未使用的标签错误。
--baseUrlstring解析非相对模块名的基准目录。查看模块解析文档了解详情。
--charsetstring"utf8"输入文件的字符集。
--declaration
-d
booleanfalse生成相应的'.d.ts'文件。
--declarationDirstring生成声明文件的输出路径。
--diagnosticsbooleanfalse显示诊断信息。
--disableSizeLimitbooleanfalse禁用JavaScript工程体积大小的限制
--emitBOMbooleanfalse在输出文件的开头加入BOM头(UTF-8 Byte Order Mark)。
--emitDecoratorMetadata[1]booleanfalse给源码里的装饰器声明加上设计类型元数据。查看issue #2577了解更多信息。
--experimentalDecorators[1]booleanfalse实验性启用ES7装饰器支持。
--forceConsistentCasingInFileNamesbooleanfalse不允许不一致包装引用相同的文件。
--help
-h
打印帮助信息。
--inlineSourceMapbooleanfalse生成单个sourcemaps文件,而不是将每sourcemaps生成不同的文件。
--inlineSourcesbooleanfalse将代码与sourcemaps生成到一个文件中,要求同时设置了--inlineSourceMap--sourceMap属性。
--init初始化TypeScript项目并创建一个tsconfig.json文件。
--isolatedModulesbooleanfalse无条件地给没有解析的文件生成imports。
--jsxstring"Preserve"在'.tsx'文件里支持JSX:'React' 或 'Preserve'。查看JSX
--libstring[]编译过程中需要引入的库文件的列表。
可能的值为: 
► es5 
► es6 
► es2015 
► es7 
► es2016 
► es2017 dom webworker scripthost 
► es2015.core 
► es2015.collection 
► es2015.generator 
► es2015.iterable 
► es2015.promise 
► es2015.proxy 
► es2015.reflect 
► es2015.symbol 
► es2015.symbol.wellknown 
► es2016.array.include 
► es2017.object 
► es2017.sharedmemory 
注意:如果--lib没有指定默认库。默认库是
► For --target ES5: dom,es5,scripthost
► For --target ES6: dom,es6,dom.iterable,scripthost
--listEmittedFilesbooleanfalse打印出编译后生成文件的名字。
--listFilesbooleanfalse编译过程中打印文件名。
--localestring(platform specific)显示错误信息时使用的语言,比如:en-us。
--mapRootstring为调试器指定指定sourcemap文件的路径,而不是使用生成时的路径。当.map文件是在运行时指定的,并不同于js文件的地址时使用这个标记。指定的路径会嵌入到sourceMap里告诉调试器到哪里去找它们。
--maxNodeModuleJsDepthnumber0node_modules下的最大依赖深度搜索并加载JavaScript文件。仅适用于使用--allowJs
--module
-m
stringtarget === 'ES6' ? 'ES6' : 'commonjs'指定生成哪个模块系统代码:'commonjs','amd','system',或 'umd'或'es2015'。只有'amd'和'system'能和--outFile一起使用。当目标是ES5或以下的时候不能使用'es2015'。
--moduleResolutionstringmodule === 'amd' | 'system' | 'ES6' ? 'classic' : 'node'决定如何处理模块。或者是'node'对于Node.js/io.js,或者是'classic'(默认)。查看模块解析文档了解详情。
--newLinestring(platform specific)当生成文件时指定行结束符:'CRLF'(dos)或 'LF' (unix)。
--noEmitbooleanfalse不生成输出文件。
--noEmitHelpersbooleanfalse不在输出文件中生成用户自定义的帮助函数代码,如__extends
--noEmitOnErrorbooleanfalse报错时不生成输出文件。
--noFallthroughCasesInSwitchbooleanfalse报告switch语句的fallthrough错误。(即,不允许switch的case语句贯穿)
--noImplicitAnybooleanfalse在表达式和声明上有隐含的'any'类型时报错。
--noImplicitReturnsbooleanfalse不是函数的所有返回路径都有返回值时报错。
--noImplicitThisbooleanfalsethis表达式的值为any类型的时候,生成一个错误。
--noImplicitUseStrictbooleanfalse模块输出中不包含'use strict'指令。
--noLibbooleanfalse不包含默认的库文件(lib.d.ts)。
--noResolvebooleanfalse不把/// <reference``>或模块导入的文件加到编译文件列表。
--noUnusedLocalsbooleanfalse若有未使用的局部变量则抛错。
--noUnusedParametersbooleanfalse若有未使用的参数则抛错。
--outstring弃用。使用 --outFile 代替。
--outDirstring重定向输出目录。
--outFilestring将输出文件合并为一个文件。合并的顺序是根据传入编译器的文件顺序和///<reference``>import的文件顺序决定的。查看输出文件顺序文件了解详情。
paths[2]Object模块名到基于baseUrl的路径映射的列表。查看模块解析文档了解详情。
--preserveConstEnumsbooleanfalse保留constenum声明。查看const enums documentation了解详情。
--pretty[1]booleanfalse给错误和消息设置样式,使用颜色和上下文。
--project
-p
string编译指定目录下的项目。这个目录应该包含一个tsconfig.json文件来管理编译。查看tsconfig.json文档了解更多信息。
--reactNamespacestring"React"当目标为生成'react' JSX时,指定createElement__spread的调用对象
--removeCommentsbooleanfalse删除所有注释,除了以/!*开头的版权信息。
--rootDirstring(common root directory is computed from the list of input files)仅用来控制输出的目录结构--outDir
rootDirs[2]string[]根(root)文件夹列表,联给了代表运行时表示工程结构的内容。查看模块解析文档了解详情。
--skipLibCheckbooleanfalse不检查默认库文件(lib.d.ts)的正确性。
--skipDefaultLibCheckbooleanfalse不检查用户定义的库文件(*.d.ts)的正确性。
--sourceMapbooleanfalse生成相应的'.map'文件。
--sourceRootstring指定TypeScript源文件的路径,以便调试器定位。当TypeScript文件的位置是在运行时指定时使用此标记。路径信息会被加到sourceMap里。
--strictNullChecksbooleanfalse在严格的null检查模式下,nullundefined值不包含在任何类型里,只允许用它们自己和any来赋值(有个例外,undefined可以赋值到void)。
--stripInternal[1]booleanfalse不对具有/** @internal */ JSDoc注解的代码生成代码。
--suppressExcessPropertyErrors[1]booleanfalse阻止对对象字面量的额外属性检查。
--suppressImplicitAnyIndexErrorsbooleanfalse阻止--noImplicitAny对缺少索引签名的索引对象报错。查看issue #1232了解详情。
--target
-t
string"ES5"指定ECMAScript目标版本'ES3' (默认),'ES5',或'ES6'[1]
--traceResolutionbooleanfalse生成模块解析日志信息
--typesstring[]要包含的类型声明文件名列表。
--typeRootsstring[]要包含的类型声明文件路径列表。
--version
-v
打印编译器版本号。
--watch
-w
在监视模式下运行编译器。会监视输出文件,在它们改变时重新编译。
  • [1] 这些选项是试验性的。
  • [2] 这些选项只能在tsconfig.json里使用,不能在命令行使用。

TypeScript MSBuild编译选项

概述

编译选项可以在使用MSBuild的项目里通过MSBuild属性指定。

例子

<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
  <TypeScriptRemoveComments>false</TypeScriptRemoveComments>
  <TypeScriptSourceMap>true</TypeScriptSourceMap>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
  <TypeScriptRemoveComments>true</TypeScriptRemoveComments>
  <TypeScriptSourceMap>false</TypeScriptSourceMap>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets"
        Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets')" />

映射

编译选项MSBuild属性名称可用值
--declarationTypeScriptGeneratesDeclarations布尔值
--moduleTypeScriptModuleKindAMDCommonJsUMD 或 System
--targetTypeScriptTargetES3ES5, or ES6
--charsetTypeScriptCharset
--emitBOMTypeScriptEmitBOM布尔值
--emitDecoratorMetadataTypeScriptEmitDecoratorMetadata布尔值
--experimentalDecoratorsTypeScriptExperimentalDecorators布尔值
--inlineSourceMapTypeScriptInlineSourceMap布尔值
--inlineSourcesTypeScriptInlineSources布尔值
--locale自动的自动设置成PreferredUILang的值
--mapRootTypeScriptMapRoot文件路径
--newLineTypeScriptNewLineCRLF 或 LF
--noEmitOnErrorTypeScriptNoEmitOnError布尔值
--noEmitHelpersTypeScriptNoEmitHelpers布尔值
--noImplicitAnyTypeScriptNoImplicitAny布尔值
--noUnusedLocalsTypeScriptNoUnusedLocals布尔值
--noUnusedParametersTypeScriptNoUnusedParameters布尔值
--noLibTypeScriptNoLib布尔值
--noResolveTypeScriptNoResolve布尔值
--outTypeScriptOutFile文件路径
--outDirTypeScriptOutDir文件路径
--preserveConstEnumsTypeScriptPreserveConstEnums布尔值
--removeCommentsTypeScriptRemoveComments布尔值
--rootDirTypeScriptRootDir文件路径
--isolatedModulesTypeScriptIsolatedModules布尔值
--sourceMapTypeScriptSourceMap文件路径
--sourceRootTypeScriptSourceRoot文件路径
--strictNullChecksTypeScriptStrictNullChecks布尔值
--suppressImplicitAnyIndexErrorsTypeScriptSuppressImplicitAnyIndexErrors布尔值
--suppressExcessPropertyErrorsTypeScriptSuppressExcessPropertyErrors布尔值
--moduleResolutionTypeScriptModuleResolutionClassic or Node
--experimentalAsyncFunctionsTypeScriptExperimentalAsyncFunctions布尔值
--jsxTypeScriptJSXEmitReact or Preserve
--reactNamespaceTypeScriptReactNamespacestring
--skipDefaultLibCheckTypeScriptSkipDefaultLibCheck布尔值
--allowUnusedLabelsTypeScriptAllowUnusedLabels布尔值
--noImplicitReturnsTypeScriptNoImplicitReturns布尔值
--noFallthroughCasesInSwitchTypeScriptNoFallthroughCasesInSwitch布尔值
--allowUnreachableCodeTypeScriptAllowUnreachableCode布尔值
--forceConsistentCasingInFileNamesTypeScriptForceConsistentCasingInFileNames布尔值
--allowSyntheticDefaultImportsTypeScriptAllowSyntheticDefaultImports布尔值
--noImplicitUseStrictTypeScriptNoImplicitUseStrict布尔值
--projectVS不支持
--watchVS不支持
--diagnosticsVS不支持
--listFilesVS不支持
--noEmitVS不支持
--allowJsVS不支持
VS特有选项TypeScriptAdditionalFlags任意编译选项

我使用的Visual Studio版本里支持哪些选项?

查找 C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets文件。 可用的MSBuild XML标签与相应的tsc编译选项的映射都在那里。

ToolsVersion

工程文件里的<TypeScriptToolsVersion>1.7</TypeScriptToolsVersion>属性值表明了构建时使用的编译器的版本号(这个例子里是1.7) 这样就允许一个工程在不同的机器上使用固定的版本去编译。

如果没有指定TypeScriptToolsVersion,则会使用机器上安装的最新版本的编译器去构建。

如果用户使用的是更新版本的TypeScript,则会在首次加载工程的时候看到一个提示升级工程的对话框。

TypeScriptCompileBlocked

如果你使用其它的构建工具(比如,gulp, grunt等等)并且使用VS做为开发和调试工具,那么在工程里设置<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>。 这样VS只会提供给你编辑的功能,而不会在你按F5的时候去构建。

TypeScript 构建工具整合

与其它构建工具整合

Browserify

安装

npm install tsify

使用命令行交互

browserify main.ts -p [ tsify --noImplicitAny ] > bundle.js

使用API

var browserify = require("browserify");
var tsify = require("tsify");

browserify()
    .add('main.ts')
    .plugin('tsify', { noImplicitAny: true })
    .bundle()
    .pipe(process.stdout);

Duo

安装

npm install duo-typescript

使用命令行交互

duo --use duo-typescript entry.ts

使用API

var Duo = require('duo');
var fs = require('fs')
var path = require('path')
var typescript = require('duo-typescript');

var out = path.join(__dirname, "output.js")

Duo(__dirname)
    .entry('entry.ts')
    .use(typescript())
    .run(function (err, results) {
        if (err) throw err;
        // Write compiled result to output file
        fs.writeFileSync(out, results.code);
    });

Grunt

安装

npm install grunt-ts

基本Gruntfile.js

module.exports = function(grunt) {
    grunt.initConfig({
        ts: {
            default : {
                src: ["**/*.ts", "!node_modules/**/*.ts"]
            }
        }
    });
    grunt.loadNpmTasks("grunt-ts");
    grunt.registerTask("default", ["ts"]);
};

gulp

安装

npm install gulp-typescript

基本gulpfile.js

var gulp = require("gulp");
var ts = require("gulp-typescript");

gulp.task("default", function () {
    var tsResult = gulp.src("src/*.ts")
        .pipe(ts({
              noImplicitAny: true,
              out: "output.js"
        }));
    return tsResult.js.pipe(gulp.dest('built/local'));
});

jspm

安装

npm install -g jspm@beta

注意:目前jspm的0.16beta版本支持TypeScript

webpack

安装

npm install ts-loader --save-dev

基本webpack.config.js

module.exports = {
    entry: "./src/index.tsx",
    output: {
        filename: "bundle.js"
    },
    resolve: {
        // Add '.ts' and '.tsx' as a resolvable extension.
        extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
    },
    module: {
        loaders: [
            // all files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'
            { test: /\.tsx?$/, loader: "ts-loader" }
        ]
    }
};

查看更多关于ts-loader的详细信息

或者

MSBuild

更新工程文件,包含本地安装的Microsoft.TypeScript.Default.props(在顶端)和Microsoft.TypeScript.targets(在底部)文件:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <!-- Include default props at the bottom -->
  <Import
      Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.Default.props"
      Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.Default.props')" />

  <!-- TypeScript configurations go here -->
  <PropertyGroup Condition="'$(Configuration)' == 'Debug'">
    <TypeScriptRemoveComments>false</TypeScriptRemoveComments>
    <TypeScriptSourceMap>true</TypeScriptSourceMap>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)' == 'Release'">
    <TypeScriptRemoveComments>true</TypeScriptRemoveComments>
    <TypeScriptSourceMap>false</TypeScriptSourceMap>
  </PropertyGroup>

  <!-- Include default targets at the bottom -->
  <Import
      Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets"
      Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets')" />
</Project>

关于配置MSBuild编译器选项的更多详细信息,请参考:[在MSBuild里使用编译选项](./Compiler Options in MSBuild.md)

NuGet

  • 右键点击 -> Manage NuGet Packages
  • 查找Microsoft.TypeScript.MSBuild
  • 点击Install
  • 安装完成后,Rebuild。

TypeScript 每日构建

在太平洋标准时间每天午夜会自动构建TypeScript的master 分支代码并发布到NPM和NuGet上。下面将介绍如何获得并在工具里使用它们。

使用npm

npm install -g typescript@next

使用NuGet和MSBuild

注意:你需要配置工程来使用NuGet包。

有两个包:

  • Microsoft.TypeScript.Compiler:仅包含工具(tsc.exelib.d.ts ,等。)。
  • Microsoft.TypeScript.MSBuild:和上面一样的工具,还有的MSBuild的任务和目标(Microsoft.TypeScript.targets, Microsoft.TypeScript.Default.props 。,等)

更新IDE来使用每日构建

你还可以配置IDE来使用每日构建。首先你要通过npm安装包。你可以进行全局安装或者安装到本地的node_modules目录下。

下面的步骤里我们假设你已经安装好了typescript@next

Visual Studio代码

更新.vscode/settings.json如下:

"typescript.tsdk": "<path to your folder>/node_modules/typescript/lib"

详细信息参见VSCode文档 。

崇高文本

更新Settings - User如下:

"typescript_tsdk": "<path to your folder>/node_modules/typescript/lib"

Visual Studio 2013和2015

注意:大多数的改变不需要你安装新版本的VS TypeScript插件。

当前的每日构建不包含完整的插件安装包,但是我们正在试着提供每日构建的安装包。

  1. 在PowerShell命令行窗口里执行:

VS 2015:

VSDevMode.ps1 14 -tsScript <path to your folder>/node_modules/typescrip

VS 2013:

VSDevMode.ps1 12 -tsScript <path to your folder>/node_modules/typescript/lib

IntelliJ IDEA (Mac)

前往Preferences > Languages & Frameworks > TypeScript

TypeScript Version: 如果通过NPM安装:/usr/local/lib/node_modules/typescript/lib

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青少年编程作品集

你的赞赏将带来极佳的运气和才气

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值