發布於 2023-02-02

更新於 2023-02-03

程式

約810字 (5分鐘閱讀)

[譯文] 如何使 @nuxt/content 項目在部屬到伺服器時保持 createdAt 和 updatedAt 不被重置?

Title Image

Photo by Praveen Thirumurugan on Unsplash

註:Github Action 依舊無法使用此套件因為是直接部屬!!!非克隆(npm run generate)後產生 dict 資料夾進行部屬

2/3 改成用 Github Action 架設後方法就失效了!所以不適合直接部屬方法

昨天將 Blog 部屬到 GitHub Page 的時,發現了 createdAt 和 updatedAt 每次 Git 推送上去一次就會被重置,這意味著 Git 上去後並不保留 markdown 文件元數據,等同於 @nuxt/content 的 createdAt 和 updatedAt 時間戳完全失去了效果。

非常感謝 Sebastian Landwehr 的分享文章!!! 真的有夠實用,所以紀錄統整一下大概的解決方法。

英文為原作者,中文為譯文


What?

One thing I noticed when deploying the project to my server was that the createdAt and updatedAt fields were always reset and didn't reflect the actual dates.

將專案部署到服務器時我注意到的一件事是 createdAt 和 updatedAt 區塊總是被重置且沒有反映出實際日期。

Example image

大致示意圖,全部貼文時間重置都在最後推送上去的時間

Why?

The reason for this is that Git does not keep file metadata. This means that the timestamps that @nuxt/content relies on are of no use.

主要的原因為 Git 不會保留文件原始數據。這代表 @nuxt/content的時間標記是沒有作用的。

How?

- Git to the rescue!

One way to fix this is not to use the file stats, but instead use the Git history for this. Special thanks to Andrew Kreuzer for the initial idea. We check the history for each file and take the earliest commit date as createdAt and the latest as updatedAt.

靠 Git 來解救! 有一個解決此問題的方法就是不使用文件的統計數據,而是以 Git 的歷史紀錄去替代它。特別感謝 Andrew Kreuzer 最初的想法。我們檢查每個檔案的歷史紀錄,並且將最早提交數據當作 createdAt ,而最新的當作 updatedAt

Requirement for this is that Git is installed on the build system and that the history is actually checked out. There will be problems if a shallow clone is made on CI, in this case the cloning has to be configured accordingly.

這種的要求前提是要在構建系統時安裝 Git,並且有確實地檢查歷史紀錄。如果在 CI 上進行表層 Clone 會出現問題,在這種情況下,必須相應配置 Clone。

CI (Continuous Integration) : 「持續整合」的意思。主目的為利用頻繁的提交 (Commit and Push) 新功能的變動,使每次的變動都觸發自動化建置與測試,藉此找出被忽略或潛在問題,以確保最新版本是可運行的。

- Using the nuxt-content-git module to make things easy

Install the module with npm install nuxt-content-git and add it to your nuxt.config.js like this:

安裝模組 npm install nuxt-content-git 並將其安裝至 nuxt.config.js 像這樣:

export default {
  modules: [
    'nuxt-content-git',
    '@nuxt/content',
  ],
}

我是使用 yarn 進行 package 管理的,所以模組採 yarn add nuxt-content-git 進行安裝。

Note that it is important to add it before @nuxt/content, so @nuxt/content knows about the hooks that our helper module installs.

請注意,這很重要!一定要將 nuxt-content-git 新增在 @nuxt/content 前面,這樣 @nuxt/content 才了解我們輔助模塊安裝的 hook。

📚 原文連結 - Source Post Link

[1] Sebastian Landwehr's Blog

https://sebastianlandwehr.com/blog/nuxt-content-how-to-keep-createdat-and-updatedat-valid-after-cloning/

[2] Sebastian Landwehr's Medium

https://javascript.plainenglish.io/nuxt-content-how-to-keep-createdat-and-updatedat-valid-after-cloning-f80fc7e9633b

[譯文] 如何使 @nuxt/content 項目在部屬到伺服器時保持 createdAt 和 updatedAt 不被重置?

https:///blog/3

作者

Kama

Read more from 程式
lightbox-image
Toggle Button - Red Pandas Icons by svgrepo.com

Copyrights © 2023 Kama, All Rights Reserved.