為何捐款
API 瀏覽器
升級指南
NEW!
quasar.config 檔案
使用 Vite 轉換專案至 CLI
瀏覽器相容性
支援 TypeScript
目錄結構
命令列表
CSS 預處理器
路由
懶加載 - 代碼分割
處理資源
啟動檔案
預取功能
API 代理
處理 Vite
處理 process.env
使用 Pinia 進行狀態管理
使用 Vuex 進行狀態管理
Linter
測試與稽核
開發行動應用程式
Ajax 請求
公開開發伺服器
Quasar CLI 搭配 Vite - @quasar/app-vite
設定 quasar.config 檔案

請注意,您產生的專案資料夾包含一個 /quasar.config 檔案。那麼您可以透過它設定什麼呢?基本上,Quasar CLI 為您做的任何事情都可以設定。

  • 您將在您的網站/應用程式中使用的 Quasar 元件、指令和外掛程式
  • 預設的 Quasar 語言包
  • 您希望使用的圖示庫
  • Quasar 元件的預設 Quasar 圖示集
  • 開發伺服器埠口、HTTPS 模式、主機名稱等等
  • 您希望使用的CSS 動畫
  • 啟動檔案列表(也決定了執行順序)– 這些檔案位於 /src/boot 中,告訴您在掛載根 Vue 元件之前如何初始化您的應用程式
  • 要包含在捆綁包中的全域 CSS/Sass/… 檔案
  • SPA、PWA、Electron、Capacitor、Cordova、SSR、BEX(瀏覽器擴充功能)設定
  • 擴充底層工具,例如產生的 Vite 設定
  • …以及更多您將在過程中發現的功能

提示

您會注意到,變更任何這些設定都不需要您手動重新載入開發伺服器。Quasar 會偵測並重新載入必要的程序。您不會失去您的開發流程,因為您可以坐下來,Quasar CLI 會快速重新載入變更後的程式碼,甚至保持目前的狀態。這節省了您大量的時間!

警告

/quasar.config 檔案由 Quasar CLI 建置系統執行,因此這段程式碼直接在 Node 下執行,而不是在您的應用程式的上下文中執行。這表示您可以 require 像 ‘fs’、‘path’、Vite 外掛程式等等模組。請確保您想在此檔案中使用的 ES 功能受到您的 Node 版本支援(應為 >= 14.19.0)。

結構

基本概念

您會注意到 /quasar.config 檔案匯出一個函式,該函式接受一個 ctx(上下文)參數並回傳一個 Object。這允許您根據此上下文動態變更您的網站/應用程式設定

/quasar.config 檔案

module.exports = function (ctx) { // can be async too
  console.log(ctx)

  // Example output on console:
  /*
  {
    dev: true,
    prod: false,
    mode: { spa: true },
    modeName: 'spa',
    target: {},
    targetName: undefined,
    arch: {},
    archName: undefined,
    debug: undefined
  }
  */

  // context gets generated based on the parameters
  // with which you run "quasar dev" or "quasar build"

  return {
    // ... your config
  }
}

這表示,舉例來說,您可以在為特定模式(如 PWA)建置時載入一種字型,並為其他模式選擇另一種字型

/quasar.config 檔案

{
  extras: [
    ctx.mode.pwa // we're adding only if working on a PWA
      ? 'roboto-font'
      : null
  ]
}

或者,您可以為 SPA 模式使用全域 CSS 檔案,為 Cordova 模式使用另一個全域 CSS 檔案,同時避免為其他模式載入任何此類檔案。

/quasar.config 檔案

{
  css: [
    ctx.mode.spa ? 'app-spa.sass' : null, // looks for /src/css/app-spa.sass
    ctx.mode.cordova ? 'app-cordova.sass' : null  // looks for /src/css/app-cordova.sass
  ]
}

或者,您可以設定開發伺服器在 SPA 模式下於埠口 8000 執行,在 PWA 模式下於埠口 9000 執行,或在其他模式下於埠口 9090 執行

/quasar.config 檔案

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

您也可以在回傳 quasar 設定之前執行非同步工作

/quasar.config 檔案

module.exports = async function (ctx) {
  const data = await someAsyncFunction()
  return {
    // ... use "data"
  }
}

// or:
module.exports = function (ctx) {
  return new Promise(resolve => {
    // some async work then:
    // resolve() with the quasar config
    resolve({
      //
    })
  })
}

可能性是無限的。

IDE 自動完成

您可以將回傳的函式用 configure() 輔助函式包裝起來,以獲得更好的 IDE 自動完成體驗(透過 TypeScript)

/quasar.config 檔案

const { configure } = require('quasar/wrappers')

module.exports = configure(function (ctx) {
  /* configuration options */
})

可設定的選項

css

/**
 * Global CSS/Stylus/SCSS/SASS/... files from `/src/css/`,
 * except for theme files, which are included by default.
 */
css?: string[];

範例

/quasar.config 檔案

{
  css: [
    'app.sass', // referring to /src/css/app.sass
    '~some-library/style.css' // referring to node_modules/some-library/style.css
  ]
}

boot

更多資訊請參閱啟動檔案

/** Boot files to load. Order is important. */
boot?: QuasarBootConfiguration;

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

type QuasarBootConfiguration = (string | BootConfigurationItem)[];

preFetch

更多資訊請參閱PreFetch 功能頁面。

/** Enable the preFetch feature. */
preFetch?: boolean;

eslint
已棄用

警告

此屬性已被棄用,建議改用 vite-plugin-checker。

更多資訊請參閱Linter 頁面。

extras

/**
 * What to import from [@quasar/extras](https://github.com/quasarframework/quasar/tree/dev/extras) package.
 * @example ['material-icons', 'roboto-font', 'ionicons-v4']
 */
extras?: (QuasarIconSets | QuasarFonts)[];

framework

/**
 * What Quasar language pack to use, what Quasar icon
 * set to use for Quasar components, etc.
 */
framework?: QuasarFrameworkConfiguration;

interface QuasarFrameworkConfiguration {
  /**
   * @see - QuasarConfOptions tab in API cards throughout the docs
   */
  config?: SerializableConfiguration<QuasarUIConfiguration>;
  /**
   * One of the Quasar IconSets
   *
   * @see https://v2.quasar.dev/options/quasar-icon-sets
   *
   * @example 'material-icons'
   */
  iconSet?: QuasarIconSets;
  /**
   * One of the Quasar language packs
   *
   * @see https://v2.quasar.dev/options/quasar-language-packs
   *
   * @example 'en-US'
   * @example 'es'
   */
  lang?: QuasarLanguageCodes;
  /**
   * Quasar CSS addons have breakpoint aware versions of flex and spacing classes
   *
   * @see https://quasar.dev.org.tw/layout/grid/introduction-to-flexbox#flex-addons
   * @see https://quasar.dev.org.tw/style/spacing#flex-addons
   */
  cssAddon?: boolean;

  /**
   * Auto import - how to detect components in your vue files
   *   "kebab": q-carousel q-page
   *   "pascal": QCarousel QPage
   *   "combined": q-carousel QPage
   *
   * @default 'kebab'
   */
  autoImportComponentCase?: "kebab" | "pascal" | "combined";
  /**
   * Auto import - which file extensions should be interpreted as referring to Vue SFC?
   *
   * @default ['vue']
   */
  autoImportVueExtensions?: string[];
  /**
   * Auto import - which file extensions should be interpreted as referring to script files?
   *
   * @default ['js', 'jsx', 'ts', 'tsx']
   */
  autoImportScriptExtensions?: string[];
  /**
   * Treeshake Quasar's UI on dev too?
   * Recommended to leave this as false for performance reasons.
   *
   * @default false
   */
  devTreeshaking?: boolean;

  /**
   * Quasar will auto import components based on your usage.
   * But, in case you have a special case, you can manually specify Quasar components to be available everywhere.
   *
   * An example case would be having custom component definitions with plain string templates, inside .js or .ts files,
   * in which you are using Quasar components (e.g. q-avatar).
   *
   * Another example would be that dynamically rendering components depending on an API response or similar (e.g. in a CMS),
   * something like `<component :is="dynamicName">` where `dynamicName` is a string that matches a Quasar component name.
   *
   * @example ['QAvatar', 'QChip']
   */
  components?: (keyof QuasarComponents)[];
  /**
   * Quasar will auto import directives based on your usage.
   * But, in case you have a special case, you can manually specify Quasar directives to be available everywhere.
   *
   * An example case would be having custom component definitions with plain string templates, inside .js or .ts files,
   * in which you are using Quasar directives (e.g. v-intersection).
   *
   * @example ['Intersection', 'Mutation']
   */
  directives?: (keyof QuasarDirectives)[];
  /**
   * Quasar plugins to be installed. Specify the ones you are using in your app.
   *
   * @example ['Notify', 'Loading', 'Meta', 'AppFullscreen']
   */
  plugins?: (keyof QuasarPlugins)[];
}

請參閱這些參考資料以獲取更多資訊

animations

更多資訊請參閱CSS 動畫

/**
 * What Quasar CSS animations](/options/animations) to import.
 * @example [ 'bounceInLeft', 'bounceOutRight' ]
 * */
animations?: QuasarAnimationsConfiguration | 'all';

devServer

更多資訊:Vite 伺服器選項

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

/**
 * Vite "server" options.
 * Some properties are overwritten based on the Quasar mode you're using in order
 * to ensure a correct config.
 * Note: if you're proxying the development server (i.e. using a cloud IDE),
 * set the `public` setting to your public application URL.
 */
devServer?: DevServerOptions;

除了這些選項外,Quasar CLI 還會修改一些選項,您將體驗到它們與 Vite 應用程式不同的地方

使用 open 屬性以特定的瀏覽器開啟,而不是使用作業系統的預設瀏覽器(請查看支援的值)。先前連結中描述的 options 參數是您應該設定 quasar.config 檔案 > devSever > open with 的內容。一些範例

/quasar.config 檔案

// opens Google Chrome
devServer: {
  open: {
    app: { name: 'google chrome' }
  }
}

// opens Firefox
devServer: {
  open: {
    app: { name: 'firefox' }
  }
}

// opens Google Chrome and automatically deals with cross-platform issues:
const open = require('open')

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

您還可以設定自動開啟遠端 Vue Devtools

/quasar.config 檔案

devServer: {
  vueDevtools: true
}

建構

/** Build configuration options. */
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[];
  /**
   * @example 'node20'
   */
  node: string;
}

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

/* requires @quasar/app-vite 1.8+ */
type PluginEntry =
  | [pluginName: string, options?: any, runOptions?: PluginEntryRunOptions]
  | [pluginFactory: (options?: any) => Plugin, options?: any, runOptions?: PluginEntryRunOptions]
  | Plugin
  | null
  | undefined
  | false;

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

  /**
   * Extend Vite config generated by Quasar CLI.
   */
  extendViteConf?: (
    config: ViteUserConfig,
    invokeParams: InvokeParams
  ) => void;

  /**
   * Options to supply to @vitejs/plugin-vue
   *
   * @see https://v2.quasar.dev/quasar-cli-vite/handling-vite#vite-vue-plugin-options
   */
  viteVuePluginOptions?: VuePluginOptions;

  /**
   * Vite plugins
   *
   * @see https://v2.quasar.dev/quasar-cli-vite/handling-vite#adding-vite-plugins
   *
   * @example
   * [
   *   [ 'package-name', { ..options.. } ],
   *   [ require('some-plugin'), { ...options... } ]
   * ]
   */
  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 };

  /**
   * Public path of your app.
   * Use it when your public path is something else,
   * like _“<protocol>://<domain>/some/nested/folder”_ – in this case,
   * it means the distributables are in _“some/nested/folder”_ on your webserver.
   *
   * @default '/'
   */
  publicPath?: string;

  /**
   * Sets [Vue Router mode](https://router.vuejs.org/guide/essentials/history-mode.html).
   * History mode requires configuration on your deployment web server too.
   *
   * @default 'hash'
   */
  vueRouterMode?: "hash" | "history";

  /**
   * Sets Vue Router base.
   * Should not need to configure this, unless absolutely needed.
   */
  vueRouterBase?: string;
  /**
   * Automatically open remote Vue Devtools when running in development mode.
   */
  vueDevtools?: boolean;
  /**
   * Should the Vue Options API be available? If all your components only use Composition API
   * it would make sense performance-wise to disable Vue Options API for a compile speedup.
   *
   * @default true
   */
  vueOptionsAPI?: boolean;

  /**
   * Should we invalidate the Vite and ESLint cache on startup?
   * @default false
   */
  rebuildCache?: boolean;

  /**
   * Do you want to analyze the production bundles?
   * Generates and opens an HTML report.
   *
   * @default false
   */
  analyze?: boolean;

  /**
   * Folder where Quasar CLI should generate the distributables.
   * Relative path to project root directory.
   *
   * @default 'dist/{ctx.modeName}' For all modes except Cordova.
   * @default 'src-cordova/www' For Cordova mode.
   */
  distDir?: string;

  /**
   * Add properties to `process.env` that you can use in your website/app JS code.
   *
   * @see https://v2.quasar.dev/quasar-cli-vite/handling-process-env
   *
   * @example { SOMETHING: 'someValue' }
   */
  env?: { [index: string]: string };

  /**
   * Defines constants that get replaced in your app.
   *
   * @example { SOMETHING: JSON.stringify('someValue') } -> console.log(SOMETHING) // console.log('someValue')
   */
  rawDefine?: { [index: string]: string };

  /**
   * (requires @quasar/app-vite v1.1+)
   *
   * Build production assets with or without the hash part in filenames.
   * Example: "454d87bd" in "assets/index.454d87bd.js"
   *
   * When used, please be careful how you configure your web server cache strategy as
   * files will not change name so your client might get 304 (Not Modified) even when
   * it's not the case.
   *
   * Will not change anything if your Vite config already touches the
   * build.rollupOptions.output.entryFileNames/chunkFileNames/assetFileNames props.
   *
   * Gets applied to production builds only.
   *
   * Useful especially for (but not restricted to) PWA. If set to false then updating the
   * PWA will force to re-download all assets again, regardless if they were changed or
   * not (due to how Rollup works through Vite).
   *
   * @default true
   */
  useFilenameHashes?: boolean;

  /**
   * whether to inject module preload polyfill.
   * @default false
   */
  polyfillModulePreload?: boolean;

  /**
   * Ignores the public folder.
   * @default false
   */
  ignorePublicFolder?: boolean;

  /**
   * Set to `false` to disable minification, or specify the minifier to use.
   * Available options are 'terser' or 'esbuild'.
   * If set to anything but boolean false then it also applies to CSS.
   * For production only.
   * @default 'esbuild'
   */
  minify?: boolean | 'terser' | 'esbuild';

  /**
   * (requires @quasar/app-vite v1.5.2+)
   *
   * Minification options for html-minifier.
   *
   * @see https://github.com/terser/html-minifier-terser?tab=readme-ov-file#options-quick-reference for complete list of options
   *
   * @default
   *  {
   *    removeComments: true,
   *    collapseWhitespace: true,
   *    removeAttributeQuotes: true,
   *    collapseBooleanAttributes: true,
   *    removeScriptTypeAttributes: true
   *  }
   */
  htmlMinifyOptions?: HtmlMinifierOptions;

  /**
   * If `true`, a separate sourcemap file will be created. If 'inline', the
   * sourcemap will be appended to the resulting output file as data URI.
   * 'hidden' works like `true` except that the corresponding sourcemap
   * comments in the bundled files are suppressed.
   * @default false
   */
  sourcemap?: boolean | 'inline' | 'hidden';

  /**
   * Prepare external services before `$ quasar dev` command runs
   * like starting some backend or any other service that the app relies on.
   * Can use async/await or directly return a Promise.
   */
  beforeDev?: (params: QuasarHookParams) => void;

  /**
   * Run hook after Quasar dev server is started (`$ quasar dev`).
   * At this point, the dev server has been started and is available should you wish to do something with it.
   * Can use async/await or directly return a Promise.
   */
  afterDev?: (params: QuasarHookParams) => void;

  /**
   * Run hook before Quasar builds app for production (`$ quasar build`).
   * At this point, the distributables folder hasn’t been created yet.
   * Can use async/await or directly return a Promise.
   */
  beforeBuild?: (params: QuasarHookParams) => void;

  /**
   * Run hook after Quasar built app for production (`$ quasar build`).
   * At this point, the distributables folder has been created and is available
   *  should you wish to do something with it.
   * Can use async/await or directly return a Promise.
   */
  afterBuild?: (params: QuasarHookParams) => void;

  /**
   * Run hook if publishing was requested (`$ quasar build -P`),
   *  after Quasar built app for production and the afterBuild hook (if specified) was executed.
   * Can use async/await or directly return a Promise.
   * `opts` is Object of form `{arg, distDir}`,
   * where “arg” is the argument supplied (if any) to -P parameter.
   */
  onPublish?: (ops: { arg: string; distDir: string }) => void;
}

請參閱這些參考資料以獲取更多資訊

sourceFiles

sourceFiles?: QuasarSourceFilesConfiguration;

/**
 * Use this property to change the default names of some files of your website/app if you have to.
 * All paths must be relative to the root folder of your project.
 *
 * @default
 * {
 *  rootComponent: 'src/App.vue',
 *  router: 'src/router/index',
 *  store: 'src/stores/index', // for Pinia
 *  // store: 'src/store/index' // for Vuex
 *  pwaRegisterServiceWorker: 'src-pwa/register-service-worker',
 *  pwaServiceWorker: 'src-pwa/custom-service-worker',
 *  pwaManifestFile: 'src-pwa/manifest.json',
 *  electronMain: 'src-electron/electron-main',
 *  electronPreload: 'src-electron/electron-preload'
 * }
 */
interface QuasarSourceFilesConfiguration {
  rootComponent?: string;
  router?: string;
  store?: string;
  pwaRegisterServiceWorker?: string;
  pwaServiceWorker?: string;
  pwaManifestFile?: string;
  electronMain?: string;
  electronPreload?: string;
}

htmlVariables

/** Add variables that you can use in /index.html. */
htmlVariables?: Record<string, any>;

您可以定義變數,然後在 /index.html 中參考它們,如下所示

/quasar.config 檔案

module.exports = function (ctx) {
  return {
    htmlVariables: {
      myVar: 'some-content'
    }
  }
}

然後,舉例來說

/index.html

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

另一個範例

/quasar.config 檔案

module.exports = function (ctx) {
  return {
    htmlVariables: {
      title: 'test name',
      some: {
        prop: 'my-prop'
      }
    }
  }
}

然後,舉例來說

/index.html

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

Quasar 模式特定

屬性類型描述
cordova物件Cordova 特定設定
capacitor物件Quasar CLI Capacitor 特定設定
pwa物件PWA 特定設定
ssr物件SSR 特定設定
electron物件Electron 特定設定
bex物件BEX 特定設定

範例

為開發/建置設定環境變數

請參考我們文件中的新增至 process.env 章節。

新增 Vite 外掛程式

請參考處理 Vite 頁面。