欣迪

最近新的專案使用的 Nuxt 的測試版本 nuxtJs 3 beta,雖然已經出一陣子了,但是許多的周邊的官方文件仍然只支援到上一個版本。

最近在安裝 Tailwindcss 3 的時候,照 Tailwindcss 官方文件 操作了一翻。結果出現了以下錯誤:

ERROR  Cannot restart nuxt:  postcss@8 is not compatible with current version of nuxt (0.0.0). Expected: >=2.15.3   

搜尋了一下,在 stackoverflow 看到解決方法,前面幾個步驟和官網幾乎一樣,最關鍵的的點是在 nuxt.config.ts 裡面的設置。稍作簡化,步驟如下:

1. 在你的 repo 目錄下打開 treminal

安裝 module: tailwindcss, postcss@latest, autoprefixer@latest

Tailwind 官網還多安裝了 @nuxt/postcss8 ,但是這個插件有問題,我們可以先跳過

使用 npm

> npm install -D tailwindcss postcss@latest autoprefixer@latest
> npx tailwindcss init

使用 yarn

> yarn add -D tailwindcss postcss@latest autoprefixer@latest
> yarn tailwindcss init

完成這步驟後,會產生一個 tailwind.config.js 的檔案。

2. 修改 tailwind.config.js 的內容

這邊和官網一樣,設定 nuxtjs 需要監聽的檔案內容。

 //  ./tailwind.config.js
module.exports = {
  content: [
    "./components/**/*.{js,vue,ts}",
    "./layouts/**/*.vue",
    "./pages/**/*.vue",
    "./plugins/**/*.{js,ts}",
    "./nuxt.config.{js,ts}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

3. 建立 postcss.config.js

// ./postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}

4. 建立 css 檔案

在 assets/css/ 目錄下建一個 main.css 檔案。

// ./assets/css/main.css
@tailwind base;
@tailwind components;
@tailwind utilities;

5. 修改 nuxt.config.ts

這裡就是最關鍵的一步了。在 tailwindcss 官方說明是在 buildModules 裡面加入 ‘@nuxt/postcss8’,顯然 ‘@nuxt/postcss8’ 這個插件尚未支援到 nuxt 3 版本,所以我們更改設定如下:

// ./nuxt.config.ts
import { defineNuxtConfig } from 'nuxt3'

export default defineNuxtConfig({
  // 這裡會自動在 head 導入生成的 css 檔案,可以不加改用步驟 6 在 app.vue 導入
  css: ['~/assets/css/main.css'],
  // 設定改成用 postcss.config.js
  build: {
    postcss: {
      postcssOptions: require('./postcss.config.js'),
    },
  }
})

6. 在 app.vue 導入 css

這個做法會在 <head> 標籤內產生 <style> 標籤,並將 css 內容寫入。

// ./app.vue
<script setup>
import '@/assets/css/tailwind.css'
</script>

訂閱 IT-Monk

訂閱最新文章的發布消息! 😚😚😚
Loading

作者介紹 - 欣迪

欣迪

從設計到寫程式,發現自己有追求前端技巧的自虐傾向。不斷的踩坑,再從坑裡爬出來,慢慢對攀岩有點心得。 目前在多間公司擔任網站設計顧問。 同時也是網站架設公司負責人。