为什么捐赠
API 浏览器
联系站长
Quasar CLI with Vite - @quasar/app-vite
配置 quasar.config 文件

注意,你的项目文件夹中包含一个 /quasar.config 文件。那么你可以通过它配置什么呢?基本上是 Quasar CLI 能为你做的所有事情:

  • 你的网站/应用将使用的 Quasar 组件、指令和插件
  • 默认 Quasar 语言包
  • 你希望使用的 图标库
  • Quasar 组件默认 图标集
  • 开发服务器端口、HTTPS 模式、主机名等
  • 你希望使用的 CSS 动画
  • Boot 文件 列表(决定执行顺序)——这些文件位于 /src/boot,用于在挂载根 Vue 组件前初始化你的应用
  • 要包含进构建包的全局 CSS/Sass/… 文件
  • SPA、PWA、Electron、Capacitor、Cordova、SSR、BEX(浏览器扩展)等模式的配置
  • 扩展底层工具,比如生成的 Vite 配置
  • 以及你在使用过程中会发现的更多功能

TIP

你会发现更改这些设置时,无需手动重载开发服务器。Quasar 会自动检测并重载相关进程。你不会丢失开发流程,因为 Quasar CLI 会快速重载变更代码,并保持当前状态。这能为你节省大量时间!

WARNING

/quasar.config 文件由 Quasar CLI 构建系统运行,因此这些代码直接在 Node.js 下执行,而不是在你的应用上下文中。这意味着你可以直接引入诸如 node:fsnode:path、Vite 插件等模块。

结构

基础用法

你会注意到 /quasar.config 文件导出一个接收 ctx(上下文)参数的函数,并返回一个对象。这样你可以根据上下文动态更改网站/应用配置:

/quasar.config file

import { defineConfig } from "#q-app/wrappers";

export default defineConfig((ctx) => {
  // 也可以是 async
  console.log(ctx);

  // 控制台示例输出:
  /*
  {
    dev: true,
    prod: false,
    mode: { spa: true },
    modeName: 'spa',
    target: {},
    targetName: undefined,
    arch: {},
    archName: undefined,
    debug: undefined
  }
  */

  // 上下文是根据运行 "quasar dev" 或 "quasar build" 时的参数生成的

  return {
    // ... 你的配置
  };
});

这意味着,例如你可以在构建某种模式(如 PWA)时加载某个字体,而在其他模式中选择另一个:

/quasar.config file

{
  extras: [
    ctx.mode.pwa // 仅在 PWA 模式下添加
      ? "roboto-font"
      : null,
  ];
}

或者你可以在 SPA 模式中使用一个全局 CSS 文件,在 Cordova 模式中使用另一个,而其他模式则不加载任何此类文件:

/quasar.config file

{
  css: [
    ctx.mode.spa ? "app-spa.sass" : null, // 指向 /src/css/app-spa.sass
    ctx.mode.cordova ? "app-cordova.sass" : null, // 指向 /src/css/app-cordova.sass
  ];
}

或者你可以配置开发服务器在 SPA 模式使用 8000 端口,PWA 模式使用 9000 端口,其他模式使用 9090 端口:

/quasar.config file

{
  devServer: {
    port: ctx.mode.spa ? 8000 : ctx.mode.pwa ? 9000 : 9090;
  }
}

你也可以在返回配置前执行异步操作:

/quasar.config file

import { defineConfig } from '#q-app/wrappers'

export default async defineConfig((ctx) => {
  const data = await someAsyncFunction()
  return {
    // ... 使用 "data"
  }
})

// 或者:
export default defineConfig((ctx) => {
  return new Promise(resolve => {
    // 一些异步操作,然后:
    // 使用 quasar 配置调用 resolve()
    resolve({
      //
    })
  })
})

玩法无限。

IDE 自动补全

注意从 #q-app/wrappers 导入的 defineConfig。它本质上是一个 no-op 函数,但它能帮助 IDE 获得更好的自动补全体验。

/quasar.config file

import { defineConfig } from "#q-app/wrappers";

export default defineConfig((ctx) => {
  /* 配置选项 */
});

可配置项说明

css

/**
 * 全局 CSS/Stylus/SCSS/SASS/... 文件,来自 `/src/css/`。
 * 主题文件默认已包含。
 */
css?: string[];

示例:

/quasar.config file

{
  css: [
    "app.sass", // 指向 /src/css/app.sass
    "~some-library/style.css", // 指向 node_modules/some-library/style.css
  ];
}

boot

更多内容请参阅 Boot 文件

/** 要加载的 Boot 文件,顺序很重要。 */
boot?: QuasarBootConfiguration;

interface BootConfigurationItem {
  path: string;
  server?: false;
  client?: false;
}

type QuasarBootConfiguration = (string | BootConfigurationItem)[];

preFetch

更多内容请参阅 PreFetch 特性 页面。

/** 启用 preFetch 特性。 */
preFetch?: boolean;

extras

/**
 * 从 [@quasar/extras](https://github.com/quasarframework/quasar/tree/dev/extras) 包导入的项。
 * @example ['material-icons', 'roboto-font', 'ionicons-v4']
 */
extras?: (QuasarIconSets | QuasarFonts)[];

framework

/**
 * 设置 Quasar 的语言包、图标集等框架相关选项。
 */
framework?: {
  /**
   * @see - 文档中各 API 卡片的 QuasarConfOptions 选项卡
   */
  config?: SerializableConfiguration<QuasarUIConfiguration>;
  /**
   * Quasar 图标集
   *
   * @see https://v2.quasar.dev/options/quasar-icon-sets
   *
   * @example 'material-icons'
   */
  iconSet?: QuasarIconSets;
  /**
   * Quasar 语言包
   *
   * @see https://v2.quasar.dev/options/quasar-language-packs
   *
   * @example 'en-US'
   * @example 'es'
   */
  lang?: QuasarLanguageCodes;
  /**
   * Quasar CSS 附加功能:提供响应式断点感知的 flex 和 spacing 类
   *
   * @see https://v2.quasar.dev/layout/grid/introduction-to-flexbox#flex-addons
   * @see https://v2.quasar.dev/style/spacing#flex-addons
   */
  cssAddon?: boolean;

  /**
   * 自动导入 - 如何检测 vue 文件中的组件
   *   "kebab": q-carousel q-page
   *   "pascal": QCarousel QPage
   *   "combined": q-carousel QPage
   *
   * @default 'kebab'
   */
  autoImportComponentCase?: "kebab" | "pascal" | "combined";
  /**
   * 自动导入 - 哪些文件扩展名应被视为 Vue SFC?
   *
   * @default ['vue']
   */
  autoImportVueExtensions?: string[];
  /**
   * 自动导入 - 哪些文件扩展名应被视为脚本文件?
   *
   * @default ['js', 'jsx', 'ts', 'tsx']
   */
  autoImportScriptExtensions?: string[];
  /**
   * 是否在开发模式下也对 Quasar UI 进行 tree-shaking?
   * 出于性能考虑,建议保持 false。
   *
   * @default false
   */
  devTreeshaking?: boolean;

  /**
   * Quasar 会根据你的使用情况自动导入组件。
   * 但在某些特殊情况下,你可以手动指定全局可用的 Quasar 组件。
   *
   * 例如,在 .js 或 .ts 文件中使用纯字符串模板定义自定义组件,
   * 其中用到了 Quasar 组件(如 q-avatar)。
   *
   * 另一个例子是根据 API 响应动态渲染组件(如在 CMS 中),
   * 类似 `<component :is="dynamicName">`,其中 `dynamicName` 是匹配 Quasar 组件名的字符串。
   *
   * @example ['QAvatar', 'QChip']
   */
  components?: (keyof QuasarComponents)[];
  /**
   * Quasar 会根据你的使用情况自动导入指令。
   * 但在某些特殊情况下,你可以手动指定全局可用的 Quasar 指令。
   *
   * @example ['Intersection', 'Mutation']
   */
  directives?: (keyof QuasarDirectives)[];
  /**
   * 要安装的 Quasar 插件。指定你在应用中使用的插件。
   *
   * @example ['Notify', 'Loading', 'Meta', 'AppFullscreen']
   */
  plugins?: (keyof QuasarPlugins)[];
}

更多参考:

animations

更多内容请参阅 CSS 动画

/**
 * 要导入的 Quasar CSS 动画。
 * @example [ 'bounceInLeft', 'bounceOutRight' ]
 * */
animations?: QuasarAnimationsConfiguration | 'all';

devServer

更多信息:Vite server options

import { ServerOptions as ViteServerOptions } from "vite";
import { Options as OpenOptions } from "open";
type DevServerOptions = Omit<ViteServerOptions, "open" | "https"> & {
  open?: Omit<OpenOptions, "wait"> | boolean;
  https?: ViteServerOptions["https"] | boolean;
};

/**
 * Vite 的 "server" 选项。
 * 某些属性会根据 Quasar 模式自动覆盖以确保配置正确。
 * 注意:如果你在代理开发服务器(如云 IDE),请将 `public` 设置为你的应用公网地址。
 */
devServer?: DevServerOptions;

除了这些选项外,Quasar CLI 还会调整一些配置,你可能会发现它们与普通 Vite 应用有所不同:

使用 open 属性可以指定用特定浏览器打开,而不是使用系统默认浏览器(查看支持的值)。前述链接中描述的 options 参数即为 quasar.config 文件 > devServer > open 的配置项。示例:

/quasar.config file

// 在 Google Chrome 中打开
devServer: {
  open: {
    app: {
      name: "google chrome";
    }
  }
}

// 在 Firefox 中打开
devServer: {
  open: {
    app: {
      name: "firefox";
    }
  }
}

// 使用 open 包自动处理 Chrome 的跨平台名称:
import open from "open";

devServer: {
  open: {
    app: {
      name: open.apps.chrome;
    }
  }
}

你也可以配置自动打开远程 Vue Devtools:

/quasar.config file

devServer: {
  vueDevtools: true;
}

build

/** 构建相关配置。 */
build?: QuasarBuildConfiguration;

import { Plugin, UserConfig as ViteUserConfig } from "vite";
import { Options as VuePluginOptions } from "@vitejs/plugin-vue"

interface InvokeParams {
  isClient: boolean;
  isServer: boolean;
}

interface BuildTargetOptions {
  /**
   * @default ['es2022', 'firefox115', 'chrome115', 'safari14']
   */
  browser?: string | string[];
  /**
   * @example 'node20'
   */
  node?: string;
}

interface PluginEntryRunOptions {
  server?: boolean;
  client?: boolean;
}

type PluginEntry =
  | [pluginName: string, options?: any, runOptions?: PluginEntryRunOptions]
  | [pluginFactory: (options?: any) => Plugin, options?: any, runOptions?: PluginEntryRunOptions]
  | Plugin
  | null
  | undefined
  | false;

interface QuasarBuildConfiguration {
  /**
   * @example
   * {
   *   browser: ['es2022', 'firefox115', 'chrome115', 'safari14'],
   *   node: 'node20'
   * }
   */
  target?: BuildTargetOptions;
  /**
   * 扩展 Quasar CLI 生成的 Vite 配置。
   *
   * 你可以返回覆盖对象,也可以直接修改 config 对象。
   *
   * @example
   * ```js
   * // 返回覆盖对象
   * extendViteConf: (config) => ({
   *   optimizeDeps: {
   *     include: ['some-package']
   *   }
   * })
   * ```
   *
   * @example
   * ```js
   * // 直接修改 config 对象
   * import { mergeConfig } from 'vite'
   * // ...
   * extendViteConf(config) {
   *   config.optimizeDeps = mergeConfig(config.optimizeDeps, {
   *     include: ['some-package']
   *   }, false)
   * }
   * ```
   */
  extendViteConf?: (
    config: ViteUserConfig,
    invokeParams: InvokeParams
  ) => ViteUserConfig | void;
  /**
   * 传给 @vitejs/plugin-vue 的选项
   *
   * @see https://v2.quasar.dev/quasar-cli-vite/handling-vite#vite-vue-plugin-options
   */
  viteVuePluginOptions?: VuePluginOptions;
  /**
   * Vite 插件
   *
   * @see https://v2.quasar.dev/quasar-cli-vite/handling-vite#adding-vite-plugins
   *
   * @example
   * // ESM
   * import { somePlugin } from 'some-plugin'
   * // ...
   * [
   *   [ 'some-plugin', { ...pluginOptions... } ],
   *
   *   // 禁止在客户端或服务端线程运行(将 server/client 设为 false):
   *   [ 'some-plugin', { ...pluginOptions... }, { server: true, client: true } ],
   *
   *   [ somePlugin, { ...pluginOptions... } ],
   *
   *   // 禁止在客户端或服务端线程运行(将 server/client 设为 false):
   *   [ somePlugin, { ...pluginOptions... }, { server: true, client: true } ],
   *
   *   somePlugin({ ...pluginOptions... })
   * ]
   *
   * @example
   * // CJS
   * [
   *   [ 'some-plugin', { ...pluginOptions... } ],
   *
   *   // 禁止在客户端或服务端线程运行(将 server/client 设为 false):
   *   [ 'some-plugin', { ...pluginOptions... }, { server: true, client: true } ],
   *
   *   [ require('some-plugin'), { ...pluginOptions... } ],
   *
   *   // 禁止在客户端或服务端线程运行(将 server/client 设为 false):
   *   [ require('some-plugin'), { ...pluginOptions... }, { server: true, client: true } ],
   *
   *   require('some-plugin')({ ...pluginOptions... })
   * ]
   */
  vitePlugins?: PluginEntry[];
  /**
   * @see https://v2.quasar.dev/quasar-cli-vite/handling-vite#folder-aliases
   *
   * @example
   * {
   *   // import { ... } from 'locales/...'
   *   locales: path.join(__dirname, 'src/locales')
   * }
   */
  alias?: { [key: string]: string };
  /**
   * TypeScript 集成配置。
   */
  typescript?: {
    /**
     * 当你的代码库完全使用 TypeScript 且所有团队成员都已适应后,
     * 你可以将此项设为 `true` 来启用更严格的类型检查。
     * 建议同时设为 `true` 并使用更严格的 typescript-eslint 规则。
     *
     * 将会设置以下 TypeScript 选项:
     * - "strict": true
     * - "allowUnreachableCode": false
     * - "allowUnusedLabels": false
     * - "noImplicitOverride": true
     * - "exactOptionalPropertyTypes": true
     * - "noUncheckedIndexedAccess": true
     *
     * @see https://www.typescriptlang.org/docs/handbook/migrating-from-javascript.html#getting-stricter-checks
     */
    strict?: boolean;

    /**
     * 扩展自动生成的 `.quasar/tsconfig.json` 文件。
     *
     * 如果没有动态逻辑需求,你可以直接修改你的 `tsconfig.json` 文件。
     */
    extendTsConfig?: (tsConfig: TSConfig) => void;

    /**
     * 为 `*.vue` 文件生成 shim 文件,将其作为普通 Vue 组件实例处理。
     *
     * Vue Language Tools VS Code 扩展可以更好地分析 `*.vue` 文件,无需 shim 文件。
     * 因此你可以禁用 shim 文件生成,让扩展来处理类型。
     *
     * 但是,某些工具(如 ESLint)在没有 shim 文件的情况下无法处理 `*.vue` 文件。
     * 如果你的工具链不能正常工作,请启用此选项。
     */
    vueShim?: boolean;
  };
  /**
   * 应用的公共路径。
   * 当你的公共路径不是根路径时使用,
   * 如 _"<protocol>://<domain>/some/nested/folder"_ —— 这种情况下,
   * 意味着构建产物位于你 Web 服务器上的 _"some/nested/folder"_ 目录下。
   *
   * @default '/'
   */
  publicPath?: string;
  /**
   * 设置 [Vue Router 模式](https://router.vuejs.org/guide/essentials/history-mode.html)。
   * History 模式还需要在部署的 Web 服务器上进行配置。
   * 对于 Capacitor 和 Electron,出于[兼容性原因](https://github.com/quasarframework/quasar/issues/17322#issuecomment-2191987962)始终使用 'hash'。
   *
   * @default 'hash'
   */
  vueRouterMode?: "hash" | "history";
  /**
   * 设置 Vue Router base。
   * 除非确实需要,否则不用配置此项。
   */
  vueRouterBase?: string;
  /**
   * 在开发模式运行时自动打开远程 Vue Devtools。
   */
  vueDevtools?: boolean;
  /**
   * 是否启用 Vue Options API?如果你的所有组件都只使用 Composition API,
   * 出于性能考虑可以禁用 Vue Options API 以加快编译速度。
   *
   * @default true
   */
  vueOptionsAPI?: boolean;
  /**
   * 是否分析生产环境构建包?
   * 会生成并打开一个 HTML 报告。
   *
   * @default false
   */
  analyze?: boolean;
  /**
   * Quasar CLI 生成构建产物的目录。
   * 相对于项目根目录的路径。
   *
   * @default 'dist/{ctx.modeName}'(除 Cordova 外的所有模式)
   * @default 'src-cordova/www'(Cordova 模式)
   */
  distDir?: string;

  /**
   * 向 `process.env` 添加属性,可在网站/应用的 JS 代码中使用。
   *
   * @see https://v2.quasar.dev/quasar-cli-vite/handling-process-env
   *
   * @example { SOMETHING: 'someValue' }
   */
  env?: { [index: string]: string | boolean | undefined | null };
  /**
   * 定义在应用中被替换的常量。
   * 与 `env` 不同,你需要自己对值使用 JSON.stringify()(布尔值除外)。
   * 而且这些常量不会以 `process.env.` 为前缀。
   *
   * @example { SOMETHING: JSON.stringify('someValue') } -> console.log(SOMETHING) // console.log('someValue')
   */
  rawDefine?: { [index: string]: string | boolean | undefined | null };
  /**
   * Quasar CLI 查找 .env* 文件的目录。
   * 可以是绝对路径或相对于项目根目录的路径。
   *
   * @default 项目根目录
   */
  envFolder?: string;
  /**
   * 要额外加载的 .env* 文件。
   * 每个条目可以是绝对路径或相对于 quasar.config > build > envFolder 的路径。
   *
   * @example ['.env.somefile', '../.env.someotherfile']
   */
  envFiles?: string[];

  /**
   * 构建生产资源时是否在文件名中包含 hash 部分。
   * 例如:在 "assets/index.454d87bd.js" 中的 "454d87bd"。
   *
   * 使用时请注意 Web 服务器缓存策略的配置,因为文件名不会变化,
   * 客户端可能会收到 304 (Not Modified) 即使实际内容已变更。
   *
   * 如果你的 Vite 配置已经修改了
   * build.rolldownOptions.output.entryFileNames/chunkFileNames/assetFileNames 属性,则此项不会产生效果。
   *
   * 仅适用于生产环境构建。
   *
   * 对 PWA 特别有用(但不限于此)。如果设为 false,更新 PWA 时会强制重新下载所有资源,
   * 不管它们是否已更改(这是 Rolldown 通过 Vite 的工作方式决定的)。
   *
   * @default true
   */
  useFilenameHashes?: boolean;

  /**
   * 是否注入模块预加载 polyfill。
   * @default false
   */
  polyfillModulePreload?: boolean;
  /**
   * 忽略 public 文件夹。
   * @default false
   */
  ignorePublicFolder?: boolean;

  /**
   * 在 `$ quasar dev` 命令运行前准备外部服务,
   * 比如启动后端服务或应用依赖的其他服务。
   * 可以使用 async/await 或直接返回 Promise。
   */
  beforeDev?: (params: QuasarHookParams) => void;
  /**
   * 在 Quasar 开发服务器启动后(`$ quasar dev`)运行的钩子。
   * 此时开发服务器已启动,你可以对其进行操作。
   * 可以使用 async/await 或直接返回 Promise。
   */
  afterDev?: (params: QuasarHookParams) => void;
  /**
   * 在 Quasar 为生产环境构建前(`$ quasar build`)运行的钩子。
   * 此时构建产物目录尚未创建。
   * 可以使用 async/await 或直接返回 Promise。
   */
  beforeBuild?: (params: QuasarHookParams) => void;
  /**
   * 在 Quasar 为生产环境构建完成后(`$ quasar build`)运行的钩子。
   * 此时构建产物目录已创建,你可以对其进行操作。
   * 可以使用 async/await 或直接返回 Promise。
   */
  afterBuild?: (params: QuasarHookParams) => void;
  /**
   * 如果请求了发布(`$ quasar build -P`),在 Quasar 完成生产构建
   * 并执行了 afterBuild 钩子(如有)后运行。
   * 可以使用 async/await 或直接返回 Promise。
   * `opts` 是形如 `{arg, distDir}` 的对象,
   * 其中 "arg" 是传给 -P 参数的值(如果有的话)。
   */
  onPublish?: (ops: { arg: string; distDir: string }) => void;

  /**
   * 设为 `false` 禁用压缩,或指定使用的压缩工具。
   * 可选值为 'terser' 或 'esbuild'。
   * 如果设为非 false 的值,则同时适用于 CSS。
   * 仅用于生产环境。
   * @default 'esbuild'
   */
  minify?: boolean | 'terser' | 'esbuild';
  /**
   * html-minifier-terser 的压缩选项。
   *
   * @see https://github.com/terser/html-minifier-terser?tab=readme-ov-file#options-quick-reference 查看完整选项列表
   *
   * @default
   *  {
   *    removeComments: true,
   *    collapseWhitespace: true,
   *    removeAttributeQuotes: true,
   *    collapseBooleanAttributes: true,
   *    removeScriptTypeAttributes: true
   *  }
   */
  htmlMinifyOptions?: HtmlMinifierOptions;
  /**
   * 如果为 `true`,会创建独立的 sourcemap 文件。如果为 'inline',
   * sourcemap 会以 data URI 形式附加到输出文件中。
   * 'hidden' 的行为类似 `true`,但会抑制打包文件中对应的 sourcemap 注释。
   * @default false
   */
  sourcemap?: boolean | 'inline' | 'hidden';
}

更多参考:

sourceFiles

/**
 * 如果需要,可以使用此属性更改网站/应用中某些文件的默认名称。
 * 所有路径都必须是相对于项目根目录的相对路径。
 *
 * @default
 * {
 *  rootComponent: 'src/App.vue',
 *  router: 'src/router/index',
 *  store: 'src/stores/index',
 *  pwaRegisterServiceWorker: 'src-pwa/register-service-worker',
 *  pwaServiceWorker: 'src-pwa/custom-service-worker',
 *  pwaManifestFile: 'src-pwa/manifest.json',
 *  electronMain: 'src-electron/electron-main',
 *  bexManifestFile: 'src-bex/manifest.json'
 * }
 */
sourceFiles?: {
  rootComponent?: string;
  router?: string;
  store?: string;
  pwaRegisterServiceWorker?: string;
  pwaServiceWorker?: string;
  pwaManifestFile?: string;
  electronMain?: string;
  bexManifestFile?: string;
}

htmlVariables

/** 添加可在 /index.html 中使用的变量。 */
htmlVariables?: Record<string, any>;

你可以定义变量,然后在 /index.html 中引用它们,示例如下:

/quasar.config file

import { defineConfig } from "#q-app/wrappers";

export default defineConfig((ctx) => {
  return {
    htmlVariables: {
      myVar: "some-content",
    },
  };
});

然后在模板中使用:

/index.html

<%= myVar %> <% if (myVar) { %>something<% } %>

再来一个例子:

/quasar.config file

htmlVariables: {
  title: 'test name',
  some: {
    prop: 'my-prop'
  }
}

然后在模板中使用:

/index.html

<%= title %> <%= some.prop %> <% if (some.prop) { %><%= title %><% } %>

Quasar 模式专属配置

属性类型说明
cordovaObjectCordova 专属 配置
capacitorObjectQuasar CLI Capacitor 专属 配置
pwaObjectPWA 专属 配置
ssrObjectSSR 专属 配置
electronObjectElectron 专属 配置
bexObjectBEX 专属 配置

示例

为开发/构建设置环境变量

请参考文档中的 添加到 process.env 部分。

添加 Vite 插件

请参考 Vite 配置处理 页面。