nuxt-tailwindcss 踩坑指南

2023/12/24

技术

安装nuxt

npx nuxi init nuxt-app

安装失败解决方法: https://juejin.cn/post/7154586714416087076

1、host文件使用管理员权限修改: win+x快捷键,使用powershell管理员权限打开hosts文件

notepad C:\Windows\System32\drivers\etc\hosts

2、在末尾添加一行185.199.108.133 raw.githubusercontent.com,保存即可

安装tailwind css

npm install -D @nuxtjs/tailwindcss

打开 ./nuxt.config.ts 将 @nuxtjs/tailwindcss 模块添加至 modules 设定参数中

export default defineNuxtConfig({
  modules: ['@nuxtjs/tailwindcss'],
})

初始化tailwind,会在根目录下生成文件 tailwind.config.js

npx tailwindcss init

./tailwind.config.js

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './components/**/*.{js,vue,ts}',
    './layouts/**/*.vue',
    './pages/**/*.vue',
    './plugins/**/*.{js,ts}',
    './app.vue',
  ],
  darkMode: 'class',
  
  theme: {
    extend: {
      colors: {
        leaf: {
          50: "#5F99F7",
          100: "#5F99F7",
        }
      }
    },
  },
  plugins: [
    require('@tailwindcss/typography'),
  ],
}
<template>
  <div class="">
  <!-- <div class="dark"> 更改class名更换为下面 dark 字段的颜色(在tailwindcss配置文件中有定义)-->
    <h1 class="text-red-500 dark:text-leaf-100">twitter clone</h1>
  </div>
</template>

路由

nuxt3通过文件结构约定了路由

./pages/
└── index/
    ├── blog/
    │   ├── [...slug].vue
    │   └── index.vue
    └── index.vue

在nuxt3中,pages目录下的每一个文件即为一个路由,文件名即为路由名,pages根目录下的index.vue为默认路由。 pages目录可创建子目录。目录的index.vue为对应的路由 ...slug.vue官网叫做catch-all route,匹配该路由下的所有子路

/:/pages/index.vue
/blog: /pages/blog/index.vue
/blog/*: /pages/blog/...slug.vue

嵌套路由

关于嵌套路由,在nuxt中也是有约定的,父路由需要创建一个同名的文件夹,然后在其中放入子路由

./pages/
└── index/
    ├── blog/
    │   ├── [...slug].vue
    │   └── index.vue
    ├── doc/
    │    └── index.vue
    └── index.vue

现在有一个两栏的布局:

<aside>
  <NuxtLink to="/blog">这是blog!</NuxtLink>
  <NuxtLink to="/blog/about">这是about</NuxtLink>
  <NuxtLink to="/doc">这是doc</NuxtLink>
</aside>

<main>
  <NuxtPage/>
</main>

在这里,/即为父路由,点击<NuxtLink/>,只有<NuxtPage/>中的内容会根据路由改变而发生变化

Nuxt content 模块

首先在项目中导入content

npm install @nuxt/content

在nuxt.config.ts中添加该模块

export default defineNuxtConfig({
  modules: [
    '@nuxtjs/tailwindcss',
    '@nuxt/content',
  ],
})

创建./content目录

./content/
└── blog/
    ├── about.md
    └── 001.md

创建./content/blog目录,该目录要对应./pages/blog 然后访问路由,例如/blog/about,因为并没有定义这个路由,所以会匹配[...slug].vue使用<ContentDoc />展示md文件的内容,要渲染内容可以使用<ContentRenderer />

<template>
    <main>
        <ContentDoc />
    </main>
</template>

contentDoc文字渲染

安装tailwindcss插件

npm i -D @tailwindcss/typography

在tailwind.config.js中添加配置

/** @type {import('tailwindcss').Config} */
export default {
  content: [
    './components/**/*.{js,vue,ts}',
    './layouts/**/*.vue',
    './pages/**/*.vue',
    './plugins/**/*.{js,ts}',
    './app.vue',
  ],
  theme: {
    extend: {},
  },
  plugins: [
    require('@tailwindcss/typography'),
  ],
}

[...slug].vue中添加样式

<template>
    <main>
        <ContentDoc class="prose"/>
    </main>
</template>

content的路由不支持纯中文

md文件为纯中文似乎不能解析,但中文混有数字或字母的就可以解析

解决方法 https://github.com/nuxt/content/issues/1383#issuecomment-1196237686

  1. 文件:./content/blog/中文.md
  2. 使用 markdownformat
---
_path: /blog/中文
---

路由:/blog/中文

ContentList 文章列表加跳转

<ContentList path="/articles" v-slot="{ list }">
    <div v-for="article in list" :key="article._path">
        <NuxtLink :to="article._path">
            <h2>{{ article.title }}</h2>
            <p>{{ article.description }}</p>
        </NuxtLink>
  </div>
</ContentList>

资源路径

字体、图片资源放在public文件夹下,使用时用/img/imge1.jpg、/fonts/font1.ttf
tailwind.css放在assets文件夹下,如~assests/css/tailwind.css

代码块高亮

https://www.boyyang.cn/detail/?id=19

安装highlight.js

npm i highlight.js

./plugins文件夹下新建highlight.ts

import hljs from 'highlight.js'
import {defineNuxtPlugin} from '#app'
import 'highlight.js/styles/base16/onedark.css'
import bash from 'highlight.js/lib/languages/bash'
// import html from 'highlight.js/lib/languages/html'
import javascript from 'highlight.js/lib/languages/javascript'
import css from 'highlight.js/lib/languages/css'
import go from 'highlight.js/lib/languages/go'
import java from 'highlight.js/lib/languages/java'
import python from 'highlight.js/lib/languages/python'
import rust from 'highlight.js/lib/languages/rust'

hljs.registerLanguage('bash',bash)
// hljs.registerLanguage('html',html)
hljs.registerLanguage('javascript',javascript)
hljs.registerLanguage('css',css)
hljs.registerLanguage('go',go)
hljs.registerLanguage('java',java)
hljs.registerLanguage('python',python)
hljs.registerLanguage('rust',rust)

export default defineNuxtPlugin((nuxtApp) => {
    nuxtApp.vueApp.directive('highlight',
        {
            mounted(el) {
                let element = el.querySelectorAll('pre code')
                element.forEach((block: HTMLElement) => {
                    if (block.dataset.highlighted === 'yes') return
                    hljs.highlightElement(block)
                })
            },
            updated(el) {
                let element = el.querySelectorAll('pre code')
                element.forEach((block: HTMLElement) => {
                    if (block.dataset.highlighted === 'yes') return
                    hljs.highlightElement(block)
                })
            },
            getSSRProps(binding, vnode) {
                // 你可以在这里提供SSR特定的props
                return {}
            },
        },
    )
})

.nuxt.config.ts配置文件中添加plugins:

plugins: [
        {
            src: '~/plugins/highlight.ts',
            mode: 'all',
        },
    ],

生产环境资源无法加载

Failed to load resource: the server responded with a status of 404 (Not Found)
https://github.com/nuxt/nuxt/issues/21974

在./nuxt.config.ts中

export default defineNuxtConfig({
  experimental: {
    payloadExtraction: false
  }
})