Nuxt3创建项目及项目配置

Nuxt3官网https://www.nuxt.com.cn/

项目相关


创建项目

$ npx nuxi init <project-name>
# or
$ pnpm dlx nuxi init <project-name>

创建成功的目录结构

project-name
├─ public
│  └─ favicon.ico
├─ server
│  └─ tsconfig.json
├─ .gitignore
├─ .npmrc
├─ README.md
├─ app.vue
├─ nuxt.config.ts
├─ package.json
└─ tsconfig.json

目录结构很简单,里面很多东西都需要自己去配置, 相关配置在下面 ↓

安装依赖项

$ yarn
# or
$ npm install
# or
$ pnpm install

运行项目

$ yarn dev -o
# or
$ npm run dev -- -o
# or
$ pnpm dev -o

配置相关


1. 配置Eslint

执行 npx eslint --init 初始化一个.eslintrc.js并自动安装相关依赖

$ npx eslint --init

---
You can also run this command directly using 'npm init @eslint/config'. 
=> To check syntax and find problems
What type of modules does your project use? 
=> JavaScript modules (import/export)
Which framework does your project use? 
=> Vue.js
Does your project use TypeScript?
=> Yes
Where does your code run?
=> Browser
What format do you want your config file to be in?
=> JavaScript
Would you like to install them now?
=> Yes

虽然nuxt3默认支持了typescript,但是用eslint还是提示Cannot find module ‘typescript’,所以需要再安装typescript依赖pnpm i -D typescript

$ pnpm i -D typescript

针对nuxt3的配置Eslint:

  1. 把配置文件中extends项下的"plugin:vue/essential"替换为"plugin:vue/vue3-recommended"(一个是vue2一个是vue3的配置)
  2. 安装 eslint-plugin-nuxt 执行 pnpm i -D eslint-plugin-nuxtextends 项中增加"plugin:nuxt/recommended",删除"eslint:recommended"(eslint默认校验)
  3. 删除plugins项下的"vue"

最终配置文件

module.exports = {
  'env': {
    'browser': true,
    'es2021': true
  },
  'extends': [
    'plugin:vue/vue3-recommended',
    'plugin:nuxt/recommended',
    'plugin:@typescript-eslint/recommended'
  ],
  'overrides': [
  ],
  'parser': 'vue-eslint-parser',
  'parserOptions': {
    'ecmaVersion': 'latest',
    'sourceType': 'module'
  },
  'plugins': [
    '@typescript-eslint'
  ],
  'rules': {
    '@typescript-eslint/ban-ts-comment': 'off',
    '@typescript-eslint/no-var-requires': 'off',
    '@typescript-eslint/interface-name-prefix': 'off',
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    'vue/multi-word-component-names': 'off',
    '@typescript-eslint/no-explicit-any': 2,
    '@typescript-eslint/no-inferrable-types': 2,
    'import/prefer-default-export': 'off',
    'import/no-mutable-exports': 'off',
    'no-alert': 2,
    'quotes': [ 2, 'single' ],
    'jsx-quotes': [ 2, 'prefer-double' ],
    'no-cond-assign': 2,
    'no-const-assign': 2,
    'no-constant-condition': 2,
    'no-delete-var': 2,
    'no-dupe-keys': 2,
    'no-dupe-args': 2,
    'no-duplicate-case': 2,
    'no-else-return': 2,
    'no-eq-null': 2,
    'no-extra-parens': 2,
    'no-ex-assign': 2,
    'no-extra-boolean-cast': 2,
    'no-extra-semi': 2,
    'no-implicit-coercion': 2,
    'no-inline-comments': 2,
    'no-func-assign': 2,
    'no-irregular-whitespace': 2,
    'no-loop-func': 1,
    'no-multiple-empty-lines': [ 2, { 'max': 1 } ],
    'no-nested-ternary': 0,
    'no-new-func': 2,
    'no-new-object': 2,
    'no-new-require': 2,
    'no-plusplus': 2,
    'no-redeclare': 2,
    'no-script-url': 0,
    'no-throw-literal': 2,
    'no-undef': 0,
    'no-undef-init': 2,
    'no-unused-vars': 0,
    'no-useless-call': 2,
    'no-void': 2,
    'no-var': 2,
    'array-bracket-spacing': [ 2, 'always' ],
    'camelcase': 2,
    'consistent-this': [ 2, 'that' ],
    'default-case': 2,
    'eqeqeq': 2,
    'func-names': 0,
    'indent': [ 2, 2 ],
    'init-declarations': 0,
    'key-spacing': [ 0, { 'beforeColon': false, 'afterColon': true } ],
    'object-curly-spacing': [ 2, 'always' ],
    'operator-linebreak': [ 2, 'after' ],
    'id-match': 0,
    'semi': [ 2, 'never' ],
    'use-isnan': 2,
    'valid-typeof': 2,
    'no-class-assign': 2,
    'space-in-parens': 2,
    'keyword-spacing': 2,
    'space-infix-ops': 2,
    'arrow-parens': [ 'error', 'as-needed' ],
    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'warn',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'warn'
  }
}

2. 配置pretter

安装prettier@vue/eslint-config-prettier

$ pnpm i -D prettier @typescript-eslint/parser

在根目录创建 .prettierrc 文件, 参考配置:

{
  "printWidth": 140, //代码单行长度
  "tabWidth": 2, //tab键缩进为2空格
  "useTabs": false, //使用空格缩进
  "singleQuote": true, //js单引号
  "semi": false, //去分号
  "trailingComma": "none", //无尾逗号
  "arrowParens": "avoid", //箭头函数尽可能省略括号
  "jsxBracketSameLine": true //标签换行后>单独一行
}

3. 代码commit前验证eslint和commitlint, 配置husky 和 commitlint

配置husky

  • 安装
    $ pnpm add husky -D
    
  • 初始化脚本
    $ pnpm exec husky init
    

配置 Lint-staged

  • 执行安装命令
    $ pnpm add lint-staged -D
    
  • 向 package.json 的 scripts 中添加命令
    $ "pre-commit": "lint-staged"
    
  • 可以根据项目需要在 package.json 中添加配置,或者根目录新建 .lintstagedrc 配置文件:
    {
      "lint-staged": {
        "*.{js,jsx,vue,ts,tsx}": [
          "eslint --fix",
          "prettier --write"
        ]
      }
     }
    
  • 将 .husky/pre-commit 脚本的内容改为
    npm run pre-commit
    

配置commitlint

  • 安装 commitlint

    $ pnpm i -D @commitlint/cli @commitlint/config-conventional
    
  • 根目录添加 commitlint.config.cjs 配置文件:

    module.exports = {
      extends: ['@commitlint/config-conventional'],
      rules: {
        'type-enum': [
          // type枚举
          2,
          'always',
          [
            'build', // 编译相关的修改,例如发布版本、对项目构建或者依赖的改动
            'feat', // 新功能
            'fix', // 修补bug
            'docs', // 文档修改
            'style', // 代码格式修改, 注意不是 css 修改
            'refactor', // 重构
            'perf', // 优化相关,比如提升性能、体验
            'test', // 测试用例修改
            'revert', // 代码回滚
            'ci', // 持续集成修改
            'config', // 配置修改
            'chore' // 其他改动
          ]
        ],
        'type-empty': [2, 'never'], // never: type不能为空; always: type必须为空
        'type-case': [0, 'always', 'lower-case'], // type必须小写,upper-case大写,camel-case小驼峰,kebab-case短横线,pascal-case大驼峰,等等
        'scope-empty': [0],
        'scope-case': [0],
        'subject-empty': [2, 'never'], // subject不能为空
        'subject-case': [0],
        'subject-full-stop': [0, 'never', '.'], // subject以.为结束标记
        'header-max-length': [2, 'always', 72], // header最长72
        'body-leading-blank': [0], // body换行
        'footer-leading-blank': [0, 'always'] // footer以空行开头
      }
    }
    
  • 向 package.json 的 scripts 中添加命令

    "scripts": { 
    	"commitlint": "commitlint --config commitlint.config.cjs -e -V" 
    }
    
  • 新增 .husky/commit-msg 配置文件

    $ npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
    
  • 加入配置

    $ npm run commitlint
    
  • 配置完成,提交代码测试一下吧

4. 创建常用目录

创建src目录
  1. 把 app.vue 文件移入到 src 目录下
  2. 修改配置文件 nuxt.config.ts
    // https://nuxt.com/docs/api/configuration/nuxt-config
    export default defineNuxtConfig({
      srcDir: 'src/',
    })
    
  3. 目录结构为
    project-name
    ├─ public
    │  └─ favicon.ico
    ├─ server
    │  └─ tsconfig.json
    ├─ src
    │  └─ app.vue
    ├─ .gitignore
    ├─ .eslintrc.js
    ├─ .npmrc
    ├─ .prettierrc
    ├─ README.md
    ├─ nuxt.config.ts
    ├─ package.json
    └─ tsconfig.json
    
  4. 配置页面路由目录pages, 在pages目录里创建页面相关文件
  5. 路由相关参考官网介绍
  6. 在src目录下创建components目录
    Nuxt默认配置自动引入, 组件调用方式如下:
    # 目录结构一
    ├─ components
    │  └─ ListView.vue
    # 对应组件调用方式
    // ...
    	<ListView />
    // ...
    
    # 目录结构二
    ├─ components
    │  └─ Custom
    │  	  └─ Button.vue
    # 对应组件调用方式
    // ...
    	<CustomButton />
    // ...
    
  7. 自定义插件
    src 目录下创建 plugins 目录
    plugins 目录下创建插件文件, 如 directives.ts
    export default defineNuxtPlugin((nuxtApp) => {
      nuxtApp.vueApp.directive('focus', {
        mounted (el) {
          el.focus()
        },
        getSSRProps (binding, vnode) {
          // you can provide SSR-specific props here
          return {}
        }
      })
    })
    
  8. 自定义 hooks
    src 目录下创建 composables 目录
    在 Nuxt 3 中使用 composables 目录时,composables/ 目录将被自动导入,将自定义的组合项(Hooks)自动导入到应用程序中,不需要再在用的地方执 import, 如在 composables 目录下创建 useLogin.ts:
    export const useLogin => () => {
      return useState('user', () => 'user')
    }
    
    # 使用方式: 在需要调用的文件执行
    <script lang="ts" setup>
    const login = userLogin()
    </script>
    
  9. 配置模板 Layouts
    src 目录下创建 default.vue 文件, 作为默认模板
    <script setup lang="ts"></script>
    
    <template>
      <div>
        This Is A Default Layout Page!
        <slot />
      </div>
    </template>
    
    <style scoped></style>
    
    使用方式
    <template>
      <NuxtLayout>
       	<!--插槽内显示的内容-->
        <NuxtPage />
      </NuxtLayout>
    </template>
    
    <script setup lang="ts"></script>
    
    自定义模板: 在 Layouts 目录下创建 layout.vue 文件
    <script setup lang="ts"></script>
    
    <template>
      <div>
        This is a custom layout named Layout!
        <slot />
      </div>
    </template>
    
    <style scoped></style>
    
    使用方式
    <template>
      <!--name为自定义的layout的文件名-->
      <NuxtLayout name="layout">
       	<!--插槽内显示的内容-->
        <NuxtPage />
      </NuxtLayout>
    </template>
    
    <script setup lang="ts"></script>
    
  10. 目录结构
    project-name
    ├─ .eslintrc.js
    ├─ .gitignore
    ├─ .npmrc
    ├─ .prettierrc
    ├─ README.md
    ├─ nuxt.config.ts
    ├─ package.json
    ├─ pnpm-lock.yaml
    ├─ public
    │  └─ favicon.ico
    ├─ server
    │  └─ tsconfig.json
    ├─ src
    │  ├─ app.vue
    │  ├─ components
    │  │  └─ Custom
    │  │     └─ Button.vue
    │  ├─ layouts
    │  │  ├─ default.vue
    │  │  └─ layout.vue
    │  ├─ pages
    │  │  └─ index.vue
    │  ├─ plugins
    ├─ tailwind.config.js
    └─ tsconfig.json
    

5. 配置 pinia

  1. 安装 pinia, 官网https://pinia.web3doc.top/
    $ pnpm install pinia @pinia/nuxt
    
  2. 修改 nuxt.config.js 文件
    @@filename(nuxt.config.ts)
    export default defineNuxtConfig({
     // ... 其他配置
    modules: [
        // ...
        '@pinia/nuxt',
      ],
    })
    
  3. src 目录下创建 stores 目录
  4. 新建 useUserStore.ts 文件
    import { defineStore } from 'pinia'
    
    export const useUserStore = defineStore('use', () => {
      const userName = ref<string>('USER_NAME')
    
      return {
        userName
      }
    })
    
  5. 使用 useUserStore
    <script setup lang="ts">
    import { useUserStore } from '@/stores'
    const userName = useUserStore().userName
    </script>
    
  6. 配置数据持久化, 安装 @pinia-plugin-persistedstate/nuxt 官网介绍
    $ pnpm i -D @pinia-plugin-persistedstate/nuxt
    # or
    $ npm i -D @pinia-plugin-persistedstate/nuxt
    # or
    $ yarn add -D @pinia-plugin-persistedstate/nuxt
    
  7. 配置 nuxt.config.ts
    export default defineNuxtConfig({
      modules: [
        '@pinia/nuxt',
        '@pinia-plugin-persistedstate/nuxt',
      ],
    })
    
  8. 使用
    import { defineStore } from 'pinia'
    
    export const useStore = defineStore('main', {
      state: () => {
        return {
          someState: 'hello pinia',
        }
      },
      persist: true,
    })
    
  9. 设置缓存方式为 localStorage
    import { defineStore } from 'pinia'
    
    export const useStore = defineStore('main', {
      state: () => {
        return {
          someState: 'hello pinia',
        }
      },
      persist: {
        storage: persistedState.localStorage,
      },
    })
    
  10. 设置缓存方式为 sessionStorage
    import { defineStore } from 'pinia'
    
    export const useStore = defineStore('main', {
      state: () => {
        return {
          someState: 'hello pinia',
        }
      },
      persist: {
        storage: persistedState.sessionStorage,
      },
    })
    
  11. 设置缓存方式为 cookiesWithOptions
    import { defineStore } from 'pinia'
    
    export const useStore = defineStore('main', {
      state: () => {
        return {
          someState: 'hello pinia',
        }
      },
      persist: {
        storage: persistedState.cookiesWithOptions({
          sameSite: 'strict',
        }),
      },
    })
    
  12. 全局配置选项
    export default defineNuxtConfig({
      modules: [
        '@pinia/nuxt',
        '@pinia-plugin-persistedstate/nuxt'
      ],
      piniaPersistedstate: {
        cookieOptions: {
          sameSite: 'strict',
        },
        storage: 'localStorage'
      },
    })
    
    • storage:设置默认用于持久保存的存储(localStorage、sessionStorage或cookies)
    • cookieOptions:默认cookie 选项(仅在保留 cookie 时使用)
    • debug: 看到了debug

6. 配置 vueuse

  1. 安装 vueuse, 官网https://www.vueusejs.com/
    $ pnpm install @vueuse/nuxt @vueuse/core
    
  2. 配置 nuxt.config.js
    @@filename(nuxt.config.js)
    export default defineNuxtConfig({
      // ... 其他配置
      modules: [
        // ...
        '@vueuse/nuxt',
      ],
    })
    
  3. 使用方式
    <script setup lang="ts">
    const { x, y } = useMouse()
    </script>
     
    <template>
      <div>pos: {{x}}, {{y}}</div>
    </template>
    

7. 配置SCSS

$ pnpm add sass sass-loader -D
注: 安装完成后直接在页面中使用即可

配置全局样式文件, 创建文件 /assets/styles/default.scss

$backgrondColor: rgb(125, 159, 172);
$theme: #ff0000;

在 nuxt.config.ts 中添加 scss 的配置

export default defineNuxtConfig({
  vite: {
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "~/assets/styles/default.scss";'	
        }
      }
    }
  }
})

8. 配置tailwindcss, 官网https://tailwindcss.com/

  1. 安装

    # 安装
    $ npm install -D tailwindcss postcss autoprefixer
    # 初始化
    $ npx tailwindcss init
    
  2. 配置 nuxt.config.ts 文件

    // https://v3.nuxtjs.org/api/configuration/nuxt.config
    export default defineNuxtConfig({
      postcss: {
        plugins: {
          tailwindcss: {},
          autoprefixer: {},
        },
      },
    })
    
  3. 配置 tailwind.config.js 文件

    /** @type {import('tailwindcss').Config} */
    module.exports = {
      content: [
        "./src/components/**/*.{vue,js}",
        "./src/layouts/**/*.vue",
        "./src/pages/**/*.vue",
        "./src/plugins/**/*.{js,ts}",
        "./nuxt.config.{js,ts}",
        "./src/app.vue"
      ],
      theme: {
        extend: {},
      },
      variants: {
        extend: {}
      },
      plugins: [],
    }
    
  4. 创建 tailwind.css 文件

     @@filename(/assets/styles/tailwind.css)
    
    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    
  5. 全局配置 tailwindcss

// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
  css: ['~/assets/styles/tailwind.css'],
  postcss: {
    plugins: {
      tailwindcss: {},
      autoprefixer: {},
    },
  },
})
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林_深时见鹿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值