Shopify Theme 的兩種開發方式 Shopify CLI 與 Theme Kit

Shopify Theme 開發官方提供的兩種方式

Shopify 官方提供了 Shopify CLI 以及 Theme Kit 兩種開發方式,Theme Kit 是比較舊的開發工具而 Shopify CLI 則是新版的開發工具。如果你開發的是 Online Store 2.0 的主題,那麼你一定得使用 Shopify CLI,當你是開發舊主題時才有可能會需要用到 Theme Kit。

Shopify Theme 的資料夾結構

Shopify 的 Theme 主題檔案主要是由 liquid 樣板語法、HTML、CSS、Javascript 所組成,Theme 資料夾結構主要分為 assets, config, layout, sections, snippets, templates,分別放置不同目的的檔案。

assets

assets 目錄包含主題中使用的所有資源,包括圖像、CSS 和 JavaScript 文件。你可以使用 asset_url Liquid URL 過濾器來引用您主題中的各種資源。如果你在 CSS 和 JavaScript 文件的副檔名加上 .liquid (.js.liquid) 和 (.css.liquid),它會讓你可以在 CSS 和 JavasScript 文件中撰寫一些 Liquid 的動態樣板語法。

config

config 資料夾是主題的設定檔案,包含了主題的所有基本設定以外也包含了使用者的操作後所儲存下來的資訊,這個地方經常會有全域性的字體、顏色設定,在 Liquid 你可以透過 settings 物件來存取它們。

layout

layout 資料架包含了主題的佈局,例如 <head> 元素是最常會被放在這裡。要注意一定需要有 theme.liquid 檔案才能夠上傳主題到 Shopify

sections

sections 資料夾是放置您自由定義的 Liquid 區塊文件,這些區塊可供使用者重複使用在頁面上。

snippets

你可以把一些常用的小片段放置在這個 snippets 資料夾,並在其他區塊中透過 Liquid render 標籤來呈現這些片段

templates

templates 資料夾會放置各種不同類型頁面所使用的版型,例如:這個資料架至少要有一個版型是要符合 product 這個類型才能夠顯示產品頁面

開始使用 Shopify CLI 開發

安裝 Shopify CLI 工具

你可以透過 ruby gem 安裝 Shopify CLI 工具、在 Mac 上你可以選擇透過 Homebrew 安裝、 Linux 上你可以選擇透過 apt, yum 安裝,取決於你的作業系統的不同自行做選擇。

# Windows, Mac, Linux 通用,會需要先安裝 Ruby 2.7 以上
gem install shopify-cli

# Mac
brew tap shopify/shopify
brew install shopify-cli

# Linux (Debian)
sudo apt install /path/to/download/shopify-cli-x.y.z.deb

# Linux (CentOS+, Fedora, Red Hat, SUSE Linux)
sudo yum install /path/to/download/shopify-cli-x.y.z.rpm

常用的 Shopify CLI 指令

  • shopify login 在使用任何指令前,需要先做帳號驗證
  • shopify theme pull 使用這個指令來下載指定的主題
  • shopify theme serve 使用這個指令在本地端開發主題
  • shopify theme push 當完成開發時,使用這個指令將本地端的 theme 覆蓋遠端指定主題
  • shopify theme publish 將本地端的主題直接做發布
  • shopify theme list 使用這個指令取得商店中所有的主題

使用 shopify theme serve 開發時會得到三個網址,分別是

  • 本地端預覽使用 127.0.0.1:9292
  • Theme Customize Editor
  • 分享給其他人預覽使用 (不需要開著也可以分享,如果要是非登入狀態的則要另外點選預覽頁面下方的提示來取得分享按鈕)

要注意的是在本地端使用 Theme Customize Editor 調整的資料並不會同步到遠端的主題,而且當你中斷本地開發後再次 shopify theme serve 會將原先調整的設定直接覆蓋掉。如果想要保留這些設定,目前得先使用 shopify theme push 覆蓋掉遠端的主題後,到遠端的主題下做 Customize,完成後再使用 shopify theme pull 將設定拉回到本地端。這個問題很惱人,但在 2022 年的三月底,Shopify 終於解決了這個問題,現在可以在 shopify theme serve 指令上加入參數 --theme-editor-sync 來做到 Two-way sync

開始使用 Theme Kit 開發

安裝 Theme Kit 工具

每個作業系統對於 themekit 的安裝方式都不相同

# Windows
choco install themekit

# Mac
brew tap shopify/shopify
brew install themekit

# Linux
curl -s https://shopify.dev/themekit.py | sudo python

Theme Kit 的使用方式

先準備好 config.yml 後,執行 theme download 可以下載指定的 theme 到本地端。這個操作要先取得 Theme Kit Password,可以到 Shopify App Store 安裝 Theme Kit Access 應用程式

development:
  password: your-theme-kit-password
  theme_id: "your-theme-id"
  store: yourdomain.myshopify.com

常用的 Theme Kit 指令

theme get 是 theme kit 的核心指令,當帶上不同參數時可以有不同的作用。例如 theme get --list 可以取得 theme 列表,而 theme get --themeid=your-theme-id 則可以下載指定的主題。其他常用的指令還有 theme deploy, theme watch, theme open...等,更多指令可以參考 Shopify 官方文件