顯示具有 Vite 標籤的文章。 顯示所有文章
顯示具有 Vite 標籤的文章。 顯示所有文章

2025年8月18日 星期一

Tailwind CSS 快速升級 v4

Tailwind CSS v4 在2025年1月推出,主打在效能上有顯著的提升,配置也變得更簡便。依照指示一步一步來調整專案,可以簡單快速完成設定。

手動升級

1. 更新及安裝套件

安裝新版的 tailwindcss@tailwindcss/postcss

npm install -D tailwindcss@4.1.12 @tailwindcss/postcss@4.1.12

兩個套件 autoprefixerpostcss 都可以從 package.json 中移除。


2. 調整 postcss.config.js

把新的套件設定放上去。

Before
export default {
  plugins: {
    "postcss-import": {}, // remove
    tailwindcss: {},      // remove
    autoprefixer: {},     // remove
  },
};
After
export default {
  plugins: {
    "@tailwindcss/postcss": {}, // new
  },
};

3. 移除 @tailwind
Before
@tailwind base;
@tailwind components;
@tailwind utilities;
After
@import "tailwindcss";

我的專案本來就沒有使用 @tailwind,因為 SASS 的 @import 準備棄用(參考資料),因此使用 @use 也效果相同。

Before
@use 'tailwindcss/base';
@use 'tailwindcss/components';
@use 'tailwindcss/utilities';
After
@use "tailwindcss";

到這邊基本上就大功告成了,可以測試看看是不是都正常呢



自動升級

另外官方這次也有提供指令來進行升級:

npx @tailwindcss/upgrade

執行時目錄內不能有任何 unstaged files,否則不會進行任何操作。可以根據Terminal上的訊息了解到執行內容基本上相同。

因此除了專案配置以外的改變,需要再參考指南確認有哪些影響,如果有v3, v4之間不兼容的調整,需要手動修正這些地方。


同場加映,額外分享兩個這次的調整:

  • Automatic content detection:過往會在tailwind.config.ts 內定義 content 偵測檔案範圍,v4不再依賴這個設定,可以大膽地把這些設定拿掉。當然!會自動忽略 .gitignore 內提及的範圍,來確保效能。
  • First-party Vite plugin:Vite目前真的可以說是強勢的存在,v4也特地為它打造一個 plugin 取代 PostCSS,只要在 vite.config.ts 加入設定,就可以移除檔案 postcss.config.js 讓專案更乾淨。

2025年8月14日 星期四

[Vue.js] SVG 引入與 Typescript 型別設定

❌錯誤示範

如何在vue專案裡使用 svg 檔案,最直覺的做法:

<template>
    <svg>
        <use href="./assets/penguin-svgrepo-com.svg" width="50%" height="50%" />
    </svg>
</template>

開發階段只要注意路徑正確,就能正常顯示。

但編譯到正式環境時,這段 <use> 標籤使用了 href="data:image/svg+xml,... 來嵌入 SVG 圖片,但這種用法在 <use> 上是無效的,因此圖示不會正確顯示。


改用圖片 <img> 來處理或許可以解決:

<img src="data:image/svg+xml,<svg ...>..." />

雖然這樣瀏覽器就會把它當成圖片正常顯示,但無法用 CSS 改 fillstroke,可調整性較差。


✔️解決方法
1. 安裝 vite-svg-loader 及設定
npm install -D vite-svg-loader

接著,vite.config.ts也要增加設定:

import svgLoader from 'vite-svg-loader';

export default {
    plugins: [
        svgLoader(),
    ],
    // ...
};

2. 新增型別宣告

假設專案並不是使用 Typescript,可以省略這個步驟。

新增 vite-env.d.ts,其主要用途是為 Vite 專案提供型別宣告。它能確保你的 TypeScript 專案能夠正確識別和處理 Vite 特有的功能,而不會報錯。

簡單來說,它就像一個翻譯官,告訴 TypeScript 編譯器:「嘿,Vite 會處理這些特殊檔案,請不要報錯,它們的型別是長這樣。」

// src/vite-env.d.ts
declare module '*.svg' {
    const content: string

    export default content
}

你也可以使用 env.d.ts。但 vite-env.d.ts 的命名方式更明確地表示它是為 Vite 專案服務的。

建議放在 src/ 資料夾的根目錄,Vite 會自動尋找資料夾中的 env.d.tsvite-env.d.ts 檔案,並將其視為專案的型別宣告。

如果你將它放在其他位置,你需要在 tsconfig.jsonincludefiles 欄位中手動指定它的路徑,確保 TypeScript 編譯器能夠找到它。

3. 使用 svg

最後只要調整引用的方法,可以把 svg 當作一個 component 來使用。

<template>
    <Penguin />
</template>

<script setup lang="ts">
import Penguin from '@/assets/penguin.svg'
</script>

這樣一來原本支援的 attr 都可以使用,例如:

<Penguin width="200" height="200" />

參考資料:


2023年3月11日 星期六

原始碼解析 create-vue 快速建立 Vue 專案


Vue 可以透過下面的指令,接著詢問一系列的問題,按照設定快速初始一個專案。(目前版本為 3.6.1)

npm init vue@latest

實際是執行這個 create-vue,想透過原始碼的解析,來了解怎麼樣做一個類似的功能,這個專案架構是如何、如何達成建立專案的功能。


1. playground

運用 git submodules的功能,主要是將各種條件下的樣板做snapshot,形成另一個 create-vue-templates 專案。


2. scripts

顧名思義分別對應到 package.json 的 scripts 所執行的檔案名。

  • build
  • prepublish
  • snapshot
  • test

3. template

將程式碼依照性質分成不同的目錄,根據使用者的設定將對應的檔案複製或合成等,形成 Vue 的專案。

  • base: 基本必備的程式碼,主要套件為 vue, vite
  • code: HelloWorld.vue 元件以及 vue-router 範例程式碼,會分成有無使用 ts 版本。
  • config: 裡面每個目錄依照套件名稱命名,目錄包含:cypress-ct, cypress, jsx, pinia, playwright, router, typescript, vitest,目錄裡是安裝套件的設定檔。主要會有 package.json 設定安裝那些套件,後續會將內容與現有設定合併,再來以 cypress 為例,會有 cypress.config.jscypress.config.ts,屆時會根據是否有用 ts 來複製對應的檔案。
  • entry: 指的是 vite 打包的 entry main.js,執行 createApp 的功能,總共有預設, pinia, router, pinia+router 這四種版本。
  • eslint
  • tsconfig

4. utils

目錄及檔案合併等方法都在這個目錄裡,檔名命名已經相當清楚。


5. index

主要邏輯在這個檔案

  • 讀 argv 指令
  • 使用 prompts 詢問一連串問題
  • 依照專案名稱等,產生 package.json
  • 複製 base
  • 複製 config
  • 複製 tsconfig
  • 產生 eslint
  • 複製 entry
  • 清除 js or ts 多餘的檔案或重新命名
  • 產生 README.md
  • 專案已完成,顯示指令提示

拆解過後,我覺得最重要的是如何整理出 template/,讓不同的安裝需求可以拆解出來,有秩序地組成這個初始的專案。


2023年1月14日 星期六

第一個 Vue3 元件測試從 Vitest + Vue Test Utils 開始

延續「mocha + webpack 的 Vue3 元件單元測試」,既然使用 mocha 測試太卡關,這次安裝 Vitest 來試試看!

一、安裝

先安裝 Vitest,另外 Vitest 需要使用 Node >=v14,並安裝 Vite >=v3.0.0,還有 vue3 對應的測試套件

npm install --save-dev vite vitest @vue/test-utils @vitejs/plugin-vue

下面這幾個根據需求來選擇是否安裝

npm install --save-dev jsdom

提供UI介面,可參考 Test UI

npm install --save-dev @vitest/ui


二、設定

先到package.json設定npm指令

"scripts": {
    "test": "npx vitest",
}

在根目錄新增檔案 vitest.config.js

import { defineConfig } from 'vite'
import Vue from '@vitejs/plugin-vue'

export default defineConfig({
    plugins: [
        Vue(),
    ],
    test: {
        globals: true,
        environment: 'jsdom',
    },
});

常用的設定像是include指定測試檔案的目錄或名稱等,和exclude排除檔案

export default defineConfig({
    test: {
        include: ['**/*.test.js'],
        exclude: ['**/node_modules/**'],
    },
});

設定路徑的alias

export default defineConfig({
    resolve: {
        alias: {
            '@': path.resolve(__dirname, 'src/'),
        },
    },
});

或者可以設定 csssetupFiles來套用css style

export default defineConfig({
    test: {
        css: true,
        setupFiles: './src/vitest/setup.js',
    },
});

src/vitest/setup.js import css

// src/vitest/setup.js

import 'todomvc-app-css/index.css';
import 'todomvc-common/base.css';

其他設定可以參考官方文件

完成基本設定後,就可以開始寫測試囉!



三、測試

針對現有的元件 TodoListEditor 撰寫測試

import { mount } from '@vue/test-utils';
import { test, expect } from 'vitest';
import TodoListEditor from 'components/TodoListEditor.vue';

test('TodoListEditor', () => {
    expect(TodoListEditor).toBeTruthy()

    const wrapper = mount(TodoListEditor, {
        props: {
            todoList,
        },
    });

    expect(wrapper.vm.todoList).toStrictEqual(todoList);
    expect(wrapper.props('todoList')).toStrictEqual(todoList);
});

參考資料



四、執行
npm run test

執行後就可以看到所有的測試項目及結果,若有錯誤也會對應的訊息顯示

有安裝@vitest/ui,可以開啟ui試試看

npm run test -- --ui


五、CI/CD

有了測試之後,我們利用 github action 設定每次 push 分支時,執行 vitest 的測試,請新增檔案 .github/workflows/test.yml

name: Test

on:
  push:
    branches: main

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Before srcipt
        run: npm install

      - name: Test
        run: npm run test -- --run

.github/workflows/gh-pages.yml內的設定:

on:
  workflow_run:
    workflows: ["Test"]
    types:
      - completed

jobs:
  build:
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    runs-on: ubuntu-latest

    steps:
      ....

我們的目標是當 Test 成功時,才會執行部屬,否則忽略。請注意 completed 指的是完成時,無論測試結果成功與否都會觸發。因此 if: ${{ github.event.workflow_run.conclusion == 'success' }} 的設定是必要的。

也可變化成 ${{ github.event.workflow_run.conclusion == 'failure' }},當測試結果失敗時可以發送通知,根據應用情境改寫。

workflows可以設定多項,只要有任何一項執行就會觸發。


安裝 Vitest 來進行 Vue3 測試十分容易。語法跟 jest 很相像,甚至原本的 mocha 寫的測試也一行都沒改,都能夠支援測試。以上的內容有上傳到 github 上(專案),可以點選下方連結了解執行的內容。