TypeScript配置-- 2. 了解ts配置项,根据vite项目了解typescript配置文件,tsconfig.json、tsconfig.node.json、

配置项目的TS

仅对于Ts项目来说,产生红色波浪线,主要是由于语法错误,当然也有其他情况…

1. 制造红色波浪线

这边先引入一个greeter.ts文件

在这里插入图片描述
发现居然没有跟一些项目一样,有红色的波浪线,不是说了函数里面的参数是需要显示追加类型的吗。
在这里插入图片描述

tsconfig.json 不知道有什么配置项?鼠标悬浮试试~~
在这里插入图片描述


2. tsconfig.json 主配置项

具体可以看官方文档:此处

在 tsconfig.json 中,第一层的配置项包括以下几个:

  1. “compilerOptions”:这是一个对象,用于配置 TypeScript 编译器的选项。它可以设置诸如目标版本、模块系统、输出目录、严格类型检查等编译器相关的选项。
  2. “files”:这是一个数组,用于指定要编译的文件列表。如果指定了这个选项,编译器将只编译列出的文件,而不会自动包含其他文件。
  3. “include”:这是一个数组,用于指定要包含在编译中的文件或文件夹的匹配模式。可以使用通配符来指定多个文件或文件夹。
  4. “exclude”:这是一个数组,用于指定要排除在编译之外的文件或文件夹的匹配模式。也可以使用通配符来排除多个文件或文件夹。
  5. “references”:这是一个数组,用于指定项目之间的引用关系。可以通过引用其他项目来实现项目之间的依赖管理。
  6. “extends”: 属性用于继承其他配置文件的设置。通过指定一个继承的配置文件路径,可以继承该配置文件中的编译选项,并且可以在当前的 tsconfig.json 文件中进行进一步的自定义。 继承包括compilerOptions,files,include,exclude。

这些配置项可以根据项目的具体需求进行设置,以实现更精细化的控制和配置。

  • extends:可以引用第三方的配置文件~
  • compilerOptions:主要的配置项
  • files,include,exclude:这三个参数主要是指定需要编译的文件 files跟include有点像,但是files只能指定文件,不能用正则,一般用不上~
  • references:用于引入其他的配置文件,例如下面将会讲解vite脚手架的项目

3. vite项目 extend\references

接下来通过vite项目来了解一下extend\references的区别

搭建项目,官网:此处
在这里插入图片描述
下面都是自动生成的代码加上注释来讲解,官网可能变动,脚手架也可能变动,所以可以先看文章,再自行操作实践
:)

3.1 tsconfig.json

根目录下的tsconfig.json是根文件,他没有什么配置,只引入了另外3个项目。

//tsconfig.json 根文件
// 可见是个空项目,用于引入其他项目
{
  "files": [],
  // 引入其他项目
  "references": [
    {
      "path": "./tsconfig.node.json"
    },
    {
      "path": "./tsconfig.app.json"
    },
    {
      "path": "./tsconfig.vitest.json"
    }
  ]
}

3.2 tsconfig.node.json

tsconfig.node.jsoninclude 可以看出,这个主要是限制配置文件的配置文件,比如vite.config.ts 的配置。

// tsconfig.node.json
{
  // 继承了npm包,ts默认的配置,ctrl+鼠标左键,可以跳过去
  "extends": "@tsconfig/node18/tsconfig.json",
  // 需要编译的文件
  "include": [
    "vite.config.*",
    "vitest.config.*",
    "cypress.config.*",
    "nightwatch.conf.*",
    "playwright.config.*"
  ],
  // 编译配置项
  "compilerOptions": {
    "composite": true,
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "types": ["node"]
  }
}

通过ctrl+鼠标左键,可以跳过去 @tsconfig/node18/tsconfig.json 文件,主要继承了compilerOptions配置项。

// @tsconfig/node18/tsconfig.json 文件
{
  "$schema": "https://json.schemastore.org/tsconfig",
  "display": "Node 18",

  "_version": "18.2.0",

  "compilerOptions": {
    "lib": ["es2023"],
    "module": "node16",
    "target": "es2022",

    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node16"
  }
}

3.3 tsconfig.app.json

通过includeexclude 可知,该文件主要为了配置我们的源码,包括 .vue 文件,所以extends 继承了 @vue/tsconfig/tsconfig.dom.json

{
  // 继承了
  "extends": "@vue/tsconfig/tsconfig.dom.json",
  "include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
  "exclude": ["src/**/__tests__/*"],
  "compilerOptions": {
    "composite": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  }
}

通过ctrl+鼠标左键,可以跳过去 @vue/tsconfig/tsconfig.dom.json 文件,主要继承了compilerOptions配置项。

// @vue/tsconfig/tsconfig.dom.json 文件
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "lib": [
      // Target ES2020 to align with Vite.
      // <https://vitejs.dev/config/build-options.html#build-target>
      // Support for newer versions of language built-ins are
      // left for the users to include, because that would require:
      //   - either the project doesn't need to support older versions of browsers;
      //   - or the project has properly included the necessary polyfills.
      "ES2020",

      "DOM",
      "DOM.Iterable"

      // No `ScriptHost` because Vue 3 dropped support for IE
    ],

    // Set to empty to avoid accidental inclusion of unwanted types
    "types": []
  }
}

再跳 @vue/tsconfig//tsconfig.json~~~这里的配置项就很充足了。

{
  "compilerOptions": {
    // As long as you are using a build tool, we recommend you to author and ship in ES modules.
    // Even if you are targeting Node.js, because
    //  - `CommonJS` is too outdated
    //  - the ecosystem hasn't fully caught up with `Node16`/`NodeNext`
    // This recommendation includes environments like Vitest, Vite Config File, Vite SSR, etc.
    "module": "ESNext",

    // We expect users to use bundlers.
    // So here we enable some resolution features that are only available in bundlers.
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    // `allowImportingTsExtensions` can only be used when `noEmit` or `emitDeclarationOnly` is set.
    // But `noEmit` may cause problems with solution-style tsconfigs:
    // <https://github.com/microsoft/TypeScript/issues/49844>
    // And `emitDeclarationOnly` is not always wanted.
    // Considering it's not likely to be commonly used in Vue codebases, we don't enable it here.

    // Required in Vue projects
    "jsx": "preserve",
    "jsxImportSource": "vue",

    // `"noImplicitThis": true` is part of `strict`
    // Added again here in case some users decide to disable `strict`.
    // This enables stricter inference for data properties on `this`.
    "noImplicitThis": true,
    "strict": true,

    // <https://devblogs.microsoft.com/typescript/announcing-typescript-5-0/#verbatimmodulesyntax>
    // Any imports or exports without a type modifier are left around. This is important for `<script setup>`.
    // Anything that uses the type modifier is dropped entirely.
    "verbatimModuleSyntax": true,

    // A few notes:
    // - Vue 3 supports ES2016+
    // - For Vite, the actual compilation target is determined by the
    //   `build.target` option in the Vite config.
    //   So don't change the `target` field here. It has to be
    //   at least `ES2020` for dynamic `import()`s and `import.meta` to work correctly.
    // - If you are not using Vite, feel free to overwrite the `target` field.
    "target": "ESNext",
    // For spec compilance.
    // `true` by default if the `target` is `ES2020` or higher.
    // Explicitly set it to `true` here in case some users want to overwrite the `target`.
    "useDefineForClassFields": true,

    // Recommended
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    // See <https://github.com/vuejs/vue-cli/pull/5688>
    "skipLibCheck": true,
  }
}

3.4 tsconfig.vitest.json

看文件名,应该是为了配置vitest 单元测试用的

**tsconfig** 的配置文件,如果没有**files\exclude\include** 会怎么怎么样呢???

// tsconfig.vitest.json 文件
{
  "extends": "./tsconfig.app.json",
  "exclude": [],
  "compilerOptions": {
    "composite": true,
    "lib": [],
    "types": ["node", "jsdom"]
  }
}

提示:

  1. 如果在 tsconfig.json 中没有配置 “files”、“include” 或 “exclude”,但是有 “compilerOptions”,则 TypeScript 编译器会默认编译当前目录下的所有 TypeScript 文件(以 .ts 或 .tsx 扩展名结尾的文件)。
  2. 如果通过references引入了多个项目,并且项目都指明了file\include\exclude 同一个源文件,将会引用最后一个references的文件。
  3. 如果通过references引入了2个项目,第一个配置文件tsconfig.app.json,涵盖了 env.d.ts文件;第二个配置文件tsconfig.vitest.json文件默认所有文件,则会执行tsconfig.app.json配置。

根据上文的引用,可知env.d.ts 执行的是tsconfig.app.json 的配置。


4. compilerOptions配置项 (持续更新~)

太多配置项了…
这边主要教大家怎么看文档~~~ 此处

在这里插入图片描述

下面枚举常用到的几个配置:

小技巧:如果在配置文件中不知道有什么选项,可以输入一个错误的值,重新运行就会提示错误,并且给你枚举出来对应的值。

在这里插入图片描述

4.1 编译相关配置

target

用来指定ts被编译成的ES版本
Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'es2021', 'es2022', 'esnext'.

{
 "compilerOptions": {
 	"target": "ES6"
 	...
 }
}
module

用来指定ts要被编译成的模块化规范,比如给服务器用的commonjs,前端常用的esm…

Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015', 'es2020', 'es2022', 'esnext', 'node16', 'nodenext'.

lib

指定项目中要用到的库,一般情况不要乱动即可。
不然你也可以试试给个空数组 :)

在这里插入图片描述
缺啥自己补啥咯,是不是跟elementUI中按需引入很相似哈哈~

outDir

用来指定编译后的输入目录。

outFile

将要编译的文件,合并成一个文件。
当然跟你配置的module配置有关,只支持amd以及system。
Only 'amd' and 'system' modules are supported alongside --outFile.

allowJs

是否对JS进行编译,默认情况只编译TS文件,开启后,匹配到的JS文件也会编译。

checkJs

是否检查JS语法。

在这里插入图片描述

removeComments

是否移除注释

noEmit

不生成编译文件,一般用于测试代码是否有问题。

noEmitOnError

TS文件就算是语法出错也是可以编译成JS文件,这个参数可以配置,当语法出错就不编译。

4.2 语法检测相关配置

总开关 strict

控制所有的检测开关,这边使用init生成文件,展示一下。
实际开发中,直接打开这个就好了,下面所有的配置都打开了。

	 /* Type Checking */
    "strict": true,                                      /* 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,               /* 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. */
alwaysStrict

开启严格模式。

noImplicitAny

回想一下,在某些地方,TypeScript 不会尝试为我们推断类型,而是退回到最宽松的类型: any。 这并不是可能发生的最糟糕的事情 - 毕竟,回退到 any 只是简单的 JavaScript 体验。

然而,使用 any 通常会破坏使用 TypeScript 的初衷。 你的程序类型越多,你获得的验证和工具就越多,这意味着你在编写代码时遇到的错误就越少。 打开 noImplicitAny 标志将对任何类型隐式推断为 any 的变量触发错误。

当你没有指定类型,并且 TypeScript 不能从上下文推断它时,编译器通常会默认为 any

不过,你通常希望避免这种情况,因为 any 没有经过类型检查。 使用编译器标志 noImplicitAny 将任何隐式 any 标记为错误。

noImplicitThis

不能直接使用this,可以通过函数参数传递。

function fn(this:Window){
	console.log(this);
}
strictNullChecks

默认情况下,像 nullundefined 这样的值可以分配给任何其他类型。 这可以使编写一些代码更容易,但忘记处理 nullundefined 是世界上无数错误的原因 - 有些人认为它是 十亿美元的错误strictNullChecks 标志使处理 nullundefined 更加明确,让我们不必担心是否忘记处理 nullundefined

let box = document.getElementById('box');
// 缩小边界
if(!!box){
	box.addEventListener('click',()=>{
		console.log("Penk666");
	})
}

// 或者使用?.操作符
box?.addEventListener('click',()=>{
	console.log("Penk666");
})

额外

主配置项冲突

files\include\exclude

tsconfig.json 中,“files”“include”“exclude” 配置项可能存在冲突。

如果同时在 “files” 中指定了特定的文件列表,并且在 “include” 或 “exclude” 中也指定了相同的文件或文件夹,那么编译器会按照以下规则进行处理:

  • 如果文件在 “files” 中指定,并且没有被 “exclude” 排除,那么它将被编译,即使它在 “include” 中没有被列出。
  • 如果文件在 “files” 中没有被指定,但在 “include” 中被列出,并且没有被 “exclude” 排除,那么它将被编译。
  • 如果文件在 “files” 中没有被指定,并且在 “include” 中也没有被列出,那么它将不会被编译,即使它在 “exclude” 中没有被排除。

因此,当存在冲突时,"files" 的配置项会起到优先级更高的作用,会覆盖 "include" 和 "exclude" 的配置。编译器将按照 "files" 中指定的文件列表进行编译,并根据 "exclude" 的配置排除相应的文件。

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Penk是个码农

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值