初始化一个vue3项目【pnpm+vite+vue3+pinia+pnpm+naive】

925 阅读6分钟

本地初始化一个vue3的项目

Vue 3 + TypeScript + Vite + pinia + pnpm + naive-ui

项目初始化

我们使用pnpm做包管理,本地未安装pnpm的,请先全局安装pnpm

npm install -g pnpm

注意vite项目要求node版本需14.8+,请注意切换自己本地的node版本。

初始化命令

pnpm create vite my-vue-app --template vue-ts

安装eslint

pnpm add eslint -D
npx eslint --init
pnpm add eslint-config-prettier -D

按照你自己的喜好,来为eslint做初始化。初始化完成后会自动生成eslintrc文件。

image.png

script标签报错:Parsing error: '>' expected.

image.png

解决办法:

pnpm add vue-eslint-parser -D

在.eslintrc文件内做如下修改,可解决此问题。

module.exports = {
        ···
	parser: 'vue-eslint-parser',
	parserOptions: {
		···
		parser: '@typescript-eslint/parser',
		···
	}

安装prettier

pnpm add prettier -D
pnpm add eslint-config-prettier -D
pnpm add eslint-plugin-prettie -D

在.eslintrc文件内做prettier 配置

module.exports = {
        ···
		extends: [
		···
		'plugin:prettier/recommended'
                ···
	]
        ···

根目录新建.prettierrc文件,按照自己的习惯配置。下面是我的配置。可做参考

{
    "printWidth": 80,
    "trailingComma": "none",
    "tabWidth": 2,
    "useTabs": true,
    "semi": false,
    "singleQuote": true,
    "bracketSpacing": true,
    "arrowParens": "avoid"
}

项目添加husky

pnpm add husky -D
npm pkg set scripts.prepare="husky install"
npm run prepare
npx husky add .husky/pre-commit "npm test"
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit "$1"'

在运行npm run prepare之前需要保证项目已做git初始化。有.git目录

image.png

项目添加lint-stage

pnpm add vue-eslint-parser -D

在package.json中添加lint命令

可放在husky中。

前面添加的这一行。和这个命令保持一致。

npx husky add .husky/pre-commit "npm test"

package.json

{
  ···
  "scripts": {
    ···
    "test": "lint-staged"
    ···
  }
}

在根目录添加.lintstagedrc


{
    "src/**/*.ts": [
        "eslint --fix",
        "prettier --write"
    ]
}

项目添加style-lint

安装一些相关依赖,可查阅官网stylelint相关配置项,安装自己需要的。我这里有用到sass。所以安装了一些sass相关的插件。这些插件作用在官网均有说明。这里不再详细。


pnpm install -D stylelint
pnpm install -D stylelint-config-standard  
pnpm install -D stylelint-config-standard-scss 
pnpm install -D postcss 
pnpm install -D postcss-scss 
pnpm install -D postcss-html  
pnpm install -D stylelint-config-standard-vue
pnpm install -D stylelint-config-prettier-scss

在根目录添加.stylelintrc.json, 配置一些自己的配置项,有些配置项可以自动格式化。 官网rules规则后面会有如下图所示的autofixable的标识

image.png

下面是我项目中使用到的配置文件,可供参考。 要想配置好stylelint还是需要好好查阅官网,了解每一个配置项,配出适合自己的。


{
    "extends": [
        "stylelint-config-standard",
        "stylelint-config-prettier"
    ],
    "rules": {
        "function-no-unknown": null,
        "selector-class-pattern": null,
        "selector-pseudo-class-no-unknown": [
            true,
            {
                "ignorePseudoClasses": [
                    "global"
                ]
            }
        ],
        "selector-pseudo-element-no-unknown": [
            true,
            {
                "ignorePseudoElements": [
                    "v-deep"
                ]
            }
        ],
        "at-rule-no-unknown": [
            true,
            {
                "ignoreAtRules": [
                    "tailwind",
                    "apply",
                    "variants",
                    "responsive",
                    "screen",
                    "function",
                    "if",
                    "each",
                    "include",
                    "mixin"
                ]
            }
        ],
        "no-empty-source": null,
        "string-quotes": null,
        "named-grid-areas-no-invalid": null,
        "unicode-bom": "never",
        "no-descending-specificity": null,
        "font-family-no-missing-generic-family-keyword": null,
        "declaration-colon-space-after": "always-single-line",
        "declaration-colon-space-before": "never",
        "rule-empty-line-before": [
            "always",
            {
                "ignore": [
                    "after-comment",
                    "first-nested"
                ]
            }
        ],
        "unit-no-unknown": [
            true,
            {
                "ignoreUnits": [
                    "rpx"
                ]
            }
        ],
        "indentation": "tab",
        "declaration-empty-line-before": "never",
        "block-closing-brace-empty-line-before": "never",
        "max-empty-lines": 1,
        "block-no-empty": true,
        "no-invalid-double-slash-comments": true
    },
    "overrides": [
        {
            "files": [
                "*.vue",
                "**/*.vue"
            ],
            "customSyntax": "postcss-html",
            "extends": [
                "stylelint-config-standard-scss",
                "stylelint-config-prettier-scss"
            ]
        },
        {
            "files": [
                "*.scss",
                "**/*.scss"
            ],
            "customSyntax": "postcss-scss",
            "extends": [
                "stylelint-config-standard-scss",
                "stylelint-config-prettier-scss"
            ]
        }
    ]
}

配置项配置好之后。需要修改编辑器来支持保存代码自动格式化css/scss文件。 我这里用的是vscode编辑器。关键配置项"source.fixAll.stylelint":true

  ···
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
    "source.fixAll.stylelint":true 
  }
  ···

vscode插件安装

不知道大家有没有注意到。用vite初始化完vue3项目之后。在项目里面会有.vscode文件夹,里面有一个extensions配置文件

image.png

vue3项目,需要使用新的语法支持插件Volar。并禁用vue2的语法插件Vetur

image.png

在这里顺带贴一份我自己的vscode配置出来。以供参考

{
  "beautify.language": {
    "js": {
      "type": ["javascript", "json"],
      "filename": [
        // 可以在项目中单独添加配置文件
        ".jshintrc",
        ".jsbeautify"
      ]
    },
    "html": ["html", "vue"]
  },
  "editor.cursorBlinking": "smooth",
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
    "source.fixAll.stylelint":true 
  },
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact"
  ],
  "eslint.alwaysShowStatus": true,
  "stylelint.validate": ["css", "less", "postcss", "scss", "vue", "sass"],
  "editor.suggestSelection": "first",
  "vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
  "files.associations": {
    "*.cjson": "jsonc",
    "*.wxss": "css",
    "*.wxs": "javascript"
  },
  "emmet.includeLanguages": {
    "wxml": "html"
  },
  "minapp-vscode.disableAutoConfig": true,
  "[json]": {
    "editor.defaultFormatter": "vscode.json-language-features"
  },
  "[vue]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescriptreact]": {
    "editor.formatOnSave": true
  },
  "diffEditor.renderSideBySide": true,
  "typescript.updateImportsOnFileMove.enabled": "always",
  "workbench.editor.showTabs": true,
  "javascript.updateImportsOnFileMove.enabled": "always",
  "gitlens.gitCommands.closeOnFocusOut": true,
  "eslint.migration.2_x": "off",
  "editor.renderWhitespace": "all",
  "workbench.colorTheme": "One Dark Pro Darker",
  "editor.fontSize": 14,
  "vsicons.dontShowNewVersionMessage": true,
  "cSpell.enableFiletypes": ["!jsonc"],
  "gitlens.views.branches.branches.layout": "list",
  "vim.insertModeKeyBindings": [
    {
      "before": ["j", "j"],
      "after": ["<Esc>"]
    }
  ],
  // "tslint.configFile": "./eslintrc.json",
  // "editor.formatOnSave": true,
  "EnglishChineseDictionary.enableHover": true,
  "[html]": {
    "editor.suggest.insertMode": "replace",
    "gitlens.codeLens.scopes": ["document"],
    "editor.defaultFormatter": "HookyQR.beautify"
  },
  "workbench.iconTheme": "Monokai Pro (Filter Machine) Icons",
  "emmet.triggerExpansionOnTab": true,
  "diffEditor.ignoreTrimWhitespace": false
}

项目添加commitlint 和 cz

commitlint 可以限制提交规范。cz可以使用命令板交互提交代码

pnpm add -@commitlint/cli
pnpm add -@commitlint/config-conventional
pnpm add -D  commitizen 
pnpm add -D  cz-customizable

在项目根目录添加commitlint.config.js

这是我的配置,可做参考。

module.exports = {
	extends: ['@commitlint/config-conventional'],
	rules: {
		'type-enum': [
			2,
			'always',
			[
				'WIP',
				'feat',
				'fix',
				'merge',
				'docs',
				'test',
				'chore',
				'refactor',
				'style',
				'perf',
				'revert'
			]
		],
		'type-case': [0],
		'type-empty': [0],
		'scope-empty': [0, 'never'],
		'scope-case': [0],
		'subject-full-stop': [0, 'never'],
		'subject-case': [0, 'never'],
		'header-max-length': [0, 'always', 72]
	}
}

在项目根目录添加.cz-config.js 这是我的配置,可做参考。

module.exports = {
	types: [
		{
			value: 'WIP',
			name: 'WIP: 工作中的提交'
		},
		{
			value: 'feat',
			name: 'feat: 新特性'
		},
		{
			value: 'fix',
			name: 'fix: 修补bug'
		},
		{
			value: 'merge',
			name: 'merge: 合并代码'
		},
		{
			value: 'docs',
			name: 'docs: 文档'
		},
		{
			value: 'refactor',
			name: 'refactor: 重构(代码优化,不影响功能)'
		},
		{
			value: 'test',
			name: 'test: 测试'
		},
		{
			value: 'chore',
			name: 'chore: 杂项 (构建工具、辅助工具的变动)'
		},
		{
			value: 'style',
			name: 'style: 代码风格调整 (如:空格,格式,分号等等)'
		},
		{
			value: 'pref',
			name: 'revert: 性能优化'
		},
		{
			value: 'revert',
			name: 'revert: 撤销提交'
		}
	],

	messages: {
		type: '请选择本次提交的类型:',
		scope: '\n请设置本次提交的任务ID或范围 (可选,E.g.:#JGRW-123,router):',
		// used if allowCustomScopes is true
		customScope: '请设置本次提交的任务ID或范围 (可选,E.g.:#JGRW-123,router):',
		subject: '请设置当前提交的简短描述:\n',
		body: '请设置当前提交的详细描述(可选). 使用 "|" 换行:\n',
		breaking: '列出任意BREAKING CHANGES (可选):\n',
		footer: '列出完成的任务ID(可选,E.g.: #JGRW-123, #JGRW-234):\n',
		confirmCommit: '确认提交?'
	},

	scopes: [],
	allowCustomScopes: true,
	allowBreakingChanges: ['feat', 'fix'],

	// 限制subject长度
	subjectLimit: 100
}

在项目package.json中添加scripts命令 以下是我的命令,可做参考

    "am": "git add .&& cz && git push",
    "m": "cz && git push",

配置完成后,可以试着提交自己的代码了

image.png

vite配置

vite不会检测本地eslint和ts报错。需要安装插件或者自己写插件来实现此功能。

我在项目里面用到了vite-plugin-checker这个插件做检查

pnpm add vite-plugin-checker -D

vite.config.ts

import checker from 'vite-plugin-checker'

export default defineConfig({
	plugins: [
		···
		checker({
			vueTsc: true,
			eslint: {
				lintCommand: 'eslint "./src/**/*.{ts,vue}"'
			}
		})
                ···
        ]
)}

vite 配置别名

注意这里不能使用require的方式导入path

import { join } from 'path'
export default defineConfig({
                ···
		resolve: {
		    alias: [
			{
				find: '@',
				replacement: join(__dirname, 'src')
			}
		    ]
	        }
                ···
)}

css预处理器导入

additionalData这里对应自己项目内的预处理器文件位置、注意单双引号和封号的位置

import { join } from 'path'
export default defineConfig({
	css: {
		preprocessorOptions: {
			scss: {
				additionalData: '@import "src/styles/var.scss";'
			}
		}
	}
)}

pinia

pnpm add pinia 

在src下面创建store文件夹,创建index文件

index.ts

import type { App } from 'vue'
import { createPinia } from 'pinia'

const store = createPinia()

export function setupStore(app: App<Element>) {
	app.use(store)
}

export store 

main.ts

import { createApp } from 'vue'

import store from '@/store'

createApp(App).use(store).mount('#app')

在store下面创建modules目录,做不同职能的状态管理

像这样来使用。用法和vuex差异不大。

interface IUserState {
	token: string
}

export const useUserStore = defineStore({
	id: 'app-user',
	state: (): IUserState => ({
		token: '',
	}),
	getters: {
		getToken(): string {
			return this.token
		}
	},
	actions: {
		setToken(token: string) {
			this.token = token
		},

		// 登录
		async login(userInfo: LoginRequest): Promise<LoginResponse | null> {
			try {
                                const data = loginApi()
				this.setToken(data.token)
				return data
			} catch (error: any) {
				return Promise.reject(error)
			}
		}
		
	}
})

naive使用

可查阅官网手册进行项目中的使用 过两天有空再写。

未完待续~~~