Skip to content

Important

core:important 插件控制 CSS 屬性值是否附加 !important 旗標。它在 transformStyleDefinitions 鉤子期間運作。

運作原理

  1. 插件在 rawConfigConfigured 期間從 EngineConfig 讀取 important.default
  2. transformStyleDefinitions 期間,對每個樣式定義:
    • 若定義中明確設定了 __important,則使用該值。
    • 否則套用 important.default 的值(預設為 false)。
  3. 當 important 為 true 時,定義中的每個屬性值都會附加 !important——包括 fallback 陣列值。
  4. __important 鍵在 CSS 輸出前始終會從定義中移除。
  5. 巢狀選擇器物件保持不變——只有屬性值會被修改。

設定

ts
interface ImportantConfig {
  /**
   * When true, all CSS values get `!important` by default.
   * Individual definitions can override this with `__important`.
   * @default false
   */
  default?: boolean
}

基本用法

全域啟用所有樣式的 !important

ts
// pika.config.ts
import { defineEngineConfig } from '@pikacss/unplugin-pikacss'

export default defineEngineConfig({
	important: {
		// When true, all CSS values get `!important` by default
		default: true,
	},
})

所有產生的 CSS 都會包含 !important

css
/* With important.default: true */
.a { color: red !important; }
.b { font-size: 1rem !important; }

逐定義覆寫

使用 __important 額外屬性,在每個定義上覆寫全域預設值:

ts
// When important.default is true, override per definition:
const noImportant = pika({
	__important: false, // disable !important for this definition
	color: 'red',
	fontSize: '1rem',
})

// When important.default is false (the default), opt-in per definition:
const withImportant = pika({
	__important: true, // enable !important for this definition
	color: 'blue',
	fontSize: '2rem',
})

產生的輸出:

css
/* With __important: false (overrides default: true) */
.a { color: red; }
.b { font-size: 1rem; }

/* With __important: true (overrides default: false) */
.c { color: blue !important; }
.d { font-size: 2rem !important; }

__important 屬性

__important 是由插件註冊的特殊額外屬性。它接受 boolean 值,且絕不會輸出至 CSS。

__importantimportant.default結果
truefalse套用 !important
truetrue套用 !important
falsefalse不套用 !important
falsetrue不套用 !important
未設定false不套用 !important
未設定true套用 !important

自動補齊

插件將 __important 作為額外屬性(附有 boolean 值)註冊,供 IDE 自動補齊使用。

原始碼參考

  • packages/core/src/internal/plugins/important.ts

Next