[Vue CLI 3] 配置之filenameHashing使用和原始碼設計

dailyvuejs發表於2018-08-30

執行 npm run build 之後的 dist 目錄的靜態資源的檔名多會追加上 hash 值,比如: page1.f151b4d3.js

那如果不要 hash 呢,你只需要配置 vue.config.js 檔案中的 filenameHashing

官方文件也提到了因為 html 也是我們通過外掛生成的,靜態資源直接就 inject 進去的,所以,當 html 不是自動生成或者其他情況時候,就不能加 hash 了,可以配置 false。

filenameHashing: false

我們看看原始碼實現:

首先它是 vue.config.js 的一個配置,在檔案 cli-service/lib/options.js 中:

預設值是 true

filenameHashing: true

先看 css 部分,在檔案 cli-service/lib/config/css.js 中:

const filename = getAssetPath(
      options,
      `css/[name]${options.filenameHashing ? `.[contenthash:8]` : ``}.css`
    )

再看 js 部分,在檔案 cli-service/lib/config/prod.js

const filename = getAssetPath(
        options,
        `js/[name]${isLegacyBundle ? `-legacy` : ``}${options.filenameHashing ? `.[contenthash:8]` : ``}.js`
      )

他們多依賴函式 getAssetPath,在檔案 util/getAssetPath.js 中定義了

const path = require(`path`)

module.exports = function getAssetPath (options, filePath, placeAtRootIfRelative) {
  return options.assetsDir
    ? path.posix.join(options.assetsDir, filePath)
    : filePath
}

相關文章