如果你在创建项目时没有选择 TypeScript 支持,你仍然可以稍后添加。本指南将向你展示如何为现有的基于 JavaScript 的 Quasar 项目添加 TypeScript 支持。
¥If you didn’t select TypeScript support when creating your project, you can still add it later. This guide will show you how to add TypeScript support to your existing JavaScript-based Quasar project.
提示
如果你在创建项目时选择了 TypeScript 支持,则可以跳过本指南。
¥If you selected TypeScript support when creating your project, you can skip this guide.
安装 TypeScript 支持(Installation of TypeScript Support)
¥Installation of TypeScript Support
安装 typescript
包:
¥Install the typescript
package:
$ yarn add --dev typescript@~5.5.3
然后,在项目根目录下创建 /tsconfig.json
文件,内容如下:
¥Then, create /tsconfig.json
file at the root of you project with this content:
{
"extends": "./.quasar/tsconfig.json"
}
在项目文件夹的根目录中运行 $ quasar prepare
。
¥Run $ quasar prepare
in the root of your project folder.
现在你可以开始在项目中使用 TypeScript。请注意,某些 IDE 可能需要重启才能完全启用新设置。
¥Now you can start using TypeScript into your project. Note that some IDEs might require a restart for the new setup to fully kick in.
提示
请记住,你必须将 JavaScript 文件的扩展名更改为 .ts
,才能在其中编写 TypeScript 代码。要在 Vue 文件中使用 TypeScript,必须更新脚本标签以包含 lang="ts"
属性,例如 <script lang="ts">
或 <script setup lang="ts">
。
¥Remember that you must change the extension of your JavaScript files to .ts
to be allowed to write TypeScript code inside them. To use TypeScript in Vue files, you must update the script tag to include the lang="ts"
attribute, like <script lang="ts">
or <script setup lang="ts">
警告
如果你忘记添加 tsconfig.json
文件,应用将在编译时崩溃!
¥If you forget to add the tsconfig.json
file, the application will break at compile time!
Linting 设置(Linting setup)
¥Linting setup
你可能需要查看 此处 的要求。
¥You might want to check the requirements for it here.
TypeScript 声明文件(TypeScript Declaration Files)
¥TypeScript Declaration Files
如果你在搭建项目脚手架时选择了 TypeScript 支持,则会自动为你搭建以下声明文件。如果在创建项目时未启用 TypeScript 支持,请创建它:
¥If you chose TypeScript support when scaffolding the project, the following declaration file was automatically scaffolded for you. If TypeScript support wasn’t enabled during project creation, create it:
declare namespace NodeJS {
interface ProcessEnv {
NODE_ENV: string;
VUE_ROUTER_MODE: 'hash' | 'history' | 'abstract' | undefined;
VUE_ROUTER_BASE: string | undefined;
// Define any custom env variables you have here, if you wish
}
}
有关你正在使用的功能和构建模式,请参阅以下部分。
¥See the following sections for the features and build modes you are using.
Pinia(Pinia)
如果你使用的是 Pinia,Quasar CLI 会自动在 .quasar/pinia.d.ts
中扩充 router
属性。请勿在 src/stores/index.ts
文件中手动从 PiniaCustomProperties
接口添加 router
属性。
¥If you are using Pinia, Quasar CLI augments the router
property inside .quasar/pinia.d.ts
automatically. So, don’t manually add the router
property from the PiniaCustomProperties
interface in the src/stores/index.ts
file.
import { defineStore } from '#q-app/wrappers'
import { createPinia } from 'pinia'
- import { type Router } from 'vue-router';
/*
* When adding new properties to stores, you should also
* extend the `PiniaCustomProperties` interface.
* @see https://pinia.vuejs.org/core-concepts/plugins.html#Typing-new-store-properties
*/
declare module 'pinia' {
export interface PiniaCustomProperties {
- readonly router: Router;
+ // add your custom properties here, if any
}
}
PWA 模式(PWA mode)
¥PWA mode
如果你正在使用 PWA 模式,请对你的项目进行以下修改,并创建任何不存在的文件:
¥If you are using PWA mode, make the following modifications to your project, and create any files that do not exist:
declare namespace NodeJS {
interface ProcessEnv {
SERVICE_WORKER_FILE: string;
PWA_FALLBACK_HTML: string;
PWA_SERVICE_WORKER_REGEX: string;
}
}
// at the top of the file
declare const self: ServiceWorkerGlobalScope &
typeof globalThis & { skipWaiting: () => void };
{
"extends": "../tsconfig.json",
"compilerOptions": {
"lib": ["WebWorker", "ESNext"]
},
"include": ["*.ts", "*.d.ts"]
}
Electron 模式(Electron mode)
¥Electron mode
如果你正在使用 Electron 模式,请将以下部分添加到你的项目中。
¥If you are using Electron mode, add the section below to your project.
declare namespace NodeJS {
interface ProcessEnv {
QUASAR_PUBLIC_FOLDER: string;
QUASAR_ELECTRON_PRELOAD_FOLDER: string;
QUASAR_ELECTRON_PRELOAD_EXTENSION: string;
APP_URL: string;
}
}
BEX 模式(BEX mode)
¥BEX mode
如果你正在使用 BEX 模式,请将以下部分添加到你的项目中。你可能需要根据所使用的事件进行调整。键是事件名称,值是一个元组,其中第一个元素是输入,第二个元素是输出类型。
¥If you are using BEX mode, add the section below to your project. You may need to adjust it to your needs depending on the events you are using. The key is the event name, the value is a tuple where the first element is the input and the second is the output type.
declare module '@quasar/app-vite' {
interface BexEventMap {
/* eslint-disable @typescript-eslint/no-explicit-any */
log: [{ message: string; data?: any[] }, never];
getTime: [never, number];
'storage.get': [{ key: string | null }, any];
'storage.set': [{ key: string; value: any }, any];
'storage.remove': [{ key: string }, any];
/* eslint-enable @typescript-eslint/no-explicit-any */
}
}
你还需要在每个内容脚本文件中使用此功能:
¥You’ll also need this in every content script file:
declare module '@quasar/app-vite' {
interface BexEventMap {
/* eslint-disable @typescript-eslint/no-explicit-any */
'some.event': [{ someProp: string }, void];
/* eslint-enable @typescript-eslint/no-explicit-any */
}
}
配置 TypeScript(Configuring TypeScript)
¥Configuring TypeScript
tsconfig.json(tsconfig.json)
请注意项目文件夹中的 /tsconfig.json
文件。Quasar CLI 使用此文件检测你是否需要 TypeScript 支持。其内容应如下所示:
¥Notice the /tsconfig.json
file in your project folder. This file is used by the Quasar CLI to detect if you want TypeScript support or not. Its content should look like this:
{
"extends": "./.quasar/tsconfig.json"
}
为了便于审查,以下是你的 /tsconfig.json
扩展的生成的 tsconfig(非严格)示例:
¥For reviewing purposes, here is an example of the generated tsconfig (non strict) that your /tsconfig.json
is extending:
{
"compilerOptions": {
"esModuleInterop": true,
"skipLibCheck": true,
"target": "esnext",
"allowJs": true,
"resolveJsonModule": true,
"moduleDetection": "force",
"isolatedModules": true,
"module": "preserve",
"noEmit": true,
"lib": [
"esnext",
"dom",
"dom.iterable"
],
"paths": { ... }
},
"exclude": [ ... ]
}
正确运行类型检查和 linting 需要 .quasar/tsconfig.json
存在。运行 quasar dev
或 quasar build
命令时,该文件将自动生成。但是,作为一种轻量级的替代方案,可以使用 CLI 命令 quasar prepare
来生成 .quasar/tsconfig.json
文件和一些类型文件。它对于 CI/CD 流水线尤其有用。
¥Properly running typechecking and linting requires the .quasar/tsconfig.json
to be present. The file will be auto-generated when running quasar dev
or quasar build
commands. But, as a lightweight alternative, there is the CLI command quasar prepare
that will generate the .quasar/tsconfig.json
file and some types files. It is especially useful for CI/CD pipelines.
$ quasar prepare
你可以将其添加为 postinstall
脚本,以确保它在安装依赖后运行。当有人第一次拉取项目时,这将很有帮助。
¥You can add it as a postinstall
script to make sure it’s run after installing the dependencies. This would be helpful when someone is pulling the project for the first time.
{
"scripts": {
"postinstall": "quasar prepare"
}
}
得益于此设置,Capacitor 依赖现在已正确链接到项目的 TypeScript 配置。这意味着你不必两次安装依赖,一次在 /src-capacitor
中,一次在根文件夹中。
¥Thanks to this setup, Capacitor dependencies are properly linked to the project’s TypeScript configuration. That means you won’t have to install dependencies twice, once in /src-capacitor
and once in the root folder.
此更改的另一个好处是 TypeScript 会自动识别文件夹别名 (quasar.config file > build > alias
)。你可以删除 tsconfig.json > compilerOptions > paths
。如果你正在使用像 vite-tsconfig-paths
这样的插件,你可以卸载它并使用 quasar.config file > build > alias
作为可信来源。
¥Another benefit of this change is that folder aliases (quasar.config file > build > alias
) are automatically recognized by TypeScript. So, you can remove tsconfig.json > compilerOptions > paths
. If you are using a plugin like vite-tsconfig-paths
, you can uninstall it and use quasar.config file > build > alias
as the source of truth.
如果你使用的是 ESLint,我们建议你在 ESLint 配置中启用 @typescript-eslint/consistent-type-imports
规则。如果你没有设置 linting,我们建议你在 tsconfig.json
文件中使用 verbatimModuleSyntax
作为替代方案(与 ESLint 规则不同,它不能自动修复)。这些更改将帮助你统一常规导入和仅类型导入。请阅读 typescript-eslint 博客 - 一致的类型导入和导出:原因和方法 了解更多信息以及如何设置。以下是示例:
¥If you are using ESLint, we recommend enabling @typescript-eslint/consistent-type-imports
rules in your ESLint configuration. If you don’t have linting set up, we recommend using verbatimModuleSyntax
in your tsconfig.json
file as an alternative (unlike ESLint rules, it’s not auto-fixable). These changes will help you unify your imports regarding regular and type-only imports. Please read typescript-eslint Blog - Consistent Type Imports and Exports: Why and How for more information about this and how to set it up. Here is an example:
rules: {
// ...
'@typescript-eslint/consistent-type-imports': [
'error',
{ prefer: 'type-imports' },
],
// ...
}
quasar.config.ts(quasar.config.ts)
你可以使用 quasar.config file > build > typescript
属性来控制与 TypeScript 相关的行为。将此部分添加到你的配置中:
¥You can use quasar.config file > build > typescript
to control the TypeScript-related behavior. Add this section into your configuration:
build: {
+ typescript: {
+ strict: true, // (recommended) enables strict settings for TypeScript
+ vueShim: true, // required when using ESLint with type-checked rules, will generate a shim file for `*.vue` files
+ extendTsConfig (tsConfig) {
+ // You can use this hook to extend tsConfig dynamically
+ // For basic use cases, you can still update the usual tsconfig.json file to override some settings
+ },
+ }
}
如果你愿意,你可以轻松将 strict
选项设置为 true
。但是,如果你遇到任何问题,你可以更新代码以满足更严格的规则,或者在 tsconfig.json
文件中将 “problematic” 选项设置为 false
,至少在你修复这些问题之前是这样。
¥Should you want, you should be able to set the strict
option to true
without facing much trouble. But, if you face any issues, you can either update your code to satisfy the stricter rules or set the “problematic” options to false
in your tsconfig.json
file, at least until you can fix them.
如果你使用带有类型检查规则的 ESLint,请启用 vueShim
选项以保留 shim 文件的先前行为。如果你的项目在没有该选项的情况下也能正常运行,则无需启用它。
¥If you are using ESLint with type-check rules, enable the vueShim
option to preserve the previous behavior with the shim file. If your project is working fine without that option, you don’t need to enable it.
build: {
typescript: {
+ vueShim: true // required when using ESLint with type-checked rules, will generate a shim file for `*.vue` files
}
}