跳轉到內容

使用 Environment 例項

候選釋出版本 (Release Candidate)

環境 API 目前處於候選釋出階段。我們將在主要版本之間保持 API 的穩定性,以便生態系統能夠進行實驗和構建。但請注意,某些特定 API 仍被視為實驗性的。

一旦下游專案有時間試驗這些新功能並完成驗證,我們計劃在未來的主要版本中穩定這些新 API(可能會有破壞性變更)。

資源

請與我們分享您的反饋。

訪問環境

在開發過程中,可以透過 server.environments 訪問開發伺服器中可用的環境。

js
// create the server, or get it from the configureServer hook
const server = await createServer(/* options */)

const clientEnvironment = server.environments.client
clientEnvironment.transformRequest(url)
console.log(server.environments.ssr.moduleGraph)

你也可以在外掛中訪問當前環境。更多詳情,請參閱外掛的環境 API

DevEnvironment

在開發過程中,每個環境都是 DevEnvironment 類的一個例項。

ts
class DevEnvironment {
  /**
   * Unique identifier for the environment in a Vite server.
   * By default Vite exposes 'client' and 'ssr' environments.
   */
  name: string
  /**
   * Communication channel to send and receive messages from the
   * associated module runner in the target runtime.
   */
  hot: NormalizedHotChannel
  /**
   * Graph of module nodes, with the imported relationship between
   * processed modules and the cached result of the processed code.
   */
  moduleGraph: EnvironmentModuleGraph
  /**
   * Resolved plugins for this environment, including the ones
   * created using the per-environment `create` hook
   */
  plugins: Plugin[]
  /**
   * Allows to resolve, load, and transform code through the
   * environment plugins pipeline
   */
  pluginContainer: EnvironmentPluginContainer
  /**
   * Resolved config options for this environment. Options at the server
   * global scope are taken as defaults for all environments, and can
   * be overridden (resolve conditions, external, optimizedDeps)
   */
  config: ResolvedConfig & ResolvedDevEnvironmentOptions

  constructor(
    name: string,
    config: ResolvedConfig,
    context: DevEnvironmentContext,
  )

  /**
   * Resolve the URL to an id, load it, and process the code using the
   * plugins pipeline. The module graph is also updated.
   */
  async transformRequest(url: string): Promise<TransformResult | null>

  /**
   * Register a request to be processed with low priority. This is useful
   * to avoid waterfalls. The Vite server has information about the
   * imported modules by other requests, so it can warmup the module graph
   * so the modules are already processed when they are requested.
   */
  async warmupRequest(url: string): Promise<void>
}

其中 DevEnvironmentContext

ts
interface DevEnvironmentContext {
  hot: boolean
  transport?: HotChannel | WebSocketServer
  options?: EnvironmentOptions
  remoteRunner?: {
    inlineSourceMap?: boolean
  }
  depsOptimizer?: DepsOptimizer
}

TransformResult

ts
interface TransformResult {
  code: string
  map: SourceMap | { mappings: '' } | null
  etag?: string
  deps?: string[]
  dynamicDeps?: string[]
}

Vite 伺服器中的環境例項允許你透過 environment.transformRequest(url) 方法來處理 URL。此函式將使用外掛流水線將 url 解析為模組 id,載入它(從檔案系統讀取檔案或透過實現虛擬模組的外掛讀取),然後轉換程式碼。在轉換模組時,匯入及其他元資料將透過建立或更新相應的模組節點記錄在環境模組圖中。處理完成後,轉換結果也會儲存在模組中。

transformRequest 的命名

我們在當前提案版本中使用 transformRequest(url)warmupRequest(url),以便於習慣 Vite 現有 API 的使用者進行討論和理解。在正式釋出之前,我們可以藉此機會審視這些名稱。例如,它可以命名為 environment.processModule(url)environment.loadModule(url),借鑑 Rollup 外掛鉤子中的 context.load(id)。目前,我們認為保留現有名稱並推遲此討論是更好的選擇。

獨立的模組圖

每個環境都有一個獨立的模組圖。所有模組圖都有相同的簽名,因此可以實現通用演算法來遍歷或查詢圖,而無需依賴於具體的環境。hotUpdate 就是一個很好的例子。當檔案被修改時,每個環境的模組圖都將被用來發現受影響的模組,併為每個環境獨立執行 HMR。

資訊

Vite v5 混合了 Client 和 SSR 模組圖。給定一個未處理或失效的節點,無法得知它對應的是 Client 環境、SSR 環境還是兩者皆是。模組節點有一些帶字首的屬性,如 clientImportedModulesssrImportedModules(以及返回兩者並集的 importedModules)。importers 包含了每個模組節點來自 Client 和 SSR 環境的所有匯入者。模組節點還擁有 transformResultssrTransformResult。向後相容層允許生態系統從已棄用的 server.moduleGraph 進行遷移。

每個模組由 EnvironmentModuleNode 例項表示。模組可以在尚未處理的情況下注冊到圖中(在這種情況下 transformResultnull)。模組處理完成後,importersimportedModules 也會隨之更新。

ts
class EnvironmentModuleNode {
  environment: string

  url: string
  id: string | null = null
  file: string | null = null

  type: 'js' | 'css'

  importers = new Set<EnvironmentModuleNode>()
  importedModules = new Set<EnvironmentModuleNode>()
  importedBindings: Map<string, Set<string>> | null = null

  info?: ModuleInfo
  meta?: Record<string, any>
  transformResult: TransformResult | null = null

  acceptedHmrDeps = new Set<EnvironmentModuleNode>()
  acceptedHmrExports: Set<string> | null = null
  isSelfAccepting?: boolean
  lastHMRTimestamp = 0
  lastInvalidationTimestamp = 0
}

environment.moduleGraphEnvironmentModuleGraph 的一個例項

ts
export class EnvironmentModuleGraph {
  environment: string

  urlToModuleMap = new Map<string, EnvironmentModuleNode>()
  idToModuleMap = new Map<string, EnvironmentModuleNode>()
  etagToModuleMap = new Map<string, EnvironmentModuleNode>()
  fileToModulesMap = new Map<string, Set<EnvironmentModuleNode>>()

  constructor(
    environment: string,
    resolveId: (url: string) => Promise<PartialResolvedId | null>,
  )

  async getModuleByUrl(
    rawUrl: string,
  ): Promise<EnvironmentModuleNode | undefined>

  getModuleById(id: string): EnvironmentModuleNode | undefined

  getModulesByFile(file: string): Set<EnvironmentModuleNode> | undefined

  onFileChange(file: string): void

  onFileDelete(file: string): void

  invalidateModule(
    mod: EnvironmentModuleNode,
    seen: Set<EnvironmentModuleNode> = new Set(),
    timestamp: number = monotonicDateNow(),
    isHmr: boolean = false,
  ): void

  invalidateAll(): void

  async ensureEntryFromUrl(
    rawUrl: string,
    setIsSelfAccepting = true,
  ): Promise<EnvironmentModuleNode>

  createFileOnlyEntry(file: string): EnvironmentModuleNode

  async resolveUrl(url: string): Promise<ResolvedUrl>

  updateModuleTransformResult(
    mod: EnvironmentModuleNode,
    result: TransformResult | null,
  ): void

  getModuleByEtag(etag: string): EnvironmentModuleNode | undefined
}