初始化vite+vue3+ts项目

1、初始化项目

npm init vite
image.png

image.png

2、安装基础依赖

vue全家桶中最新版本添加@next

npm i vue-router@next vuex@next axios sass

禁用vetur

image.png

安装volar(支持vue3语法)
image.png

3、添加git commit message校验

npm i --D yorkie

在package.json中

  "gitHooks": {
    "commit-msg": "node script/verify-commit-msg.js"
  },

在项目文件中script/verify-commit-msg.js
安装 npm i chalk -D
verify-commit-msg.js内容如下

const chalk = require('chalk')
const msgPath = process.env.GIT_PARAMS
const msg = require('fs').readFileSync(msgPath, 'utf-8').trim()

const commitRE = /^(revert: )?(feat|fix|polish|docs|style|refactor|perf|test|workflow|ci|chore|types|build)(\(.+\))?: .{1,50}/

if (!commitRE.test(msg)) {
 console.log()
 console.error(
   `  ${chalk.bgRed.white(' ERROR ')} ${chalk.red(`invalid commit message format.`)}\n\n` +
   chalk.red(`  Proper commit message format is required for automated changelog generation. Examples:\n\n`) +
   `    ${chalk.green(`feat(compiler): add 'comments' option`)}\n` +
   `    ${chalk.green(`fix(v-model): handle events on blur (close #28)`)}\n\n` +
   chalk.red(`  See .github/COMMIT_CONVENTION.md for more details.\n`) +
   chalk.red(`  You can also use ${chalk.cyan(`npm run commit`)} to interactively generate a commit message.\n`)
 )
 process.exit(1)
}

4、集成 eslint prettier stylelint

 npm i eslint prettier @vue/eslint-config-prettier eslint-plugin-prettier eslint-config-prettier eslint-plugin-vue @vue/eslint-config-typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin -D

版本报错问题:npm i @vue/eslint-config-prettier@6.* eslint-plugin-prettier@3.1.0 -D
新建文件 .eslintrc.js

module.exports = {
  root: true,
  env: {
    browser: true,
    es2021: true,
    node: true
  },
  extends: [
    'plugin:vue/vue3-recommended',
    'eslint:recommended',
    '@vue/typescript/recommended',
    '@vue/prettier',
    '@/vue/prettier/@typescript-eslint'
  ],
  // 这是初始生成的 将其中的内容更改为下面的
  parserOptions: {
    ecmaVersion: 'lastest'
  },
  globals: {
    BMap: true,
    BMapLib: true
  },
  rules: {
    // 强制第一个属性的位置(属性换行)
    'vue/first-attribute-linebreak': [
      2,
      {
        // 单行时,第一属性前不允许使用换行符
        singleline: 'ignore',
        // 多行时,第一属性前必须使用换行符
        multiline: 'below'
      }
    ],
    // 强制每行的最大属性数
    'vue/max-attributes-per-line': [
      'warn',
      {
        // 单行时可以接收最大数量
        singleline: 10,
        // 多行时可以接收最大数量
        multiline: {
          max: 1
        }
      }
    ],
    'no-unused-vars': 'off', // 未使用的变量
    'vue/multi-word-component-names': 'off', // 组件名称
    'no-undef': 'off', // 禁止使用未定义的变量
    'vue/valid-define-emits': 'off', // 组件的事件名称
    'no-var': 'off', // 禁止使用var
    'no-redeclare': 'off', // 禁止重复声明变量
    camelcase: 'off', // 强制驼峰命名
    semi: 'off', // 语句强制分号结尾
    'no-useless-escape': 'off', // 禁止不必要的转义
    'no-prototype-builtins': 'off', // 禁止直接调用 Object.prototypes 的内置属性
    eqeqeq: 'off', // 必须使用全等
    'vue/require-default-prop': 'off', // 必须设置默认值
    'node/handle-callback-err': 'off', // 回调函数错误处理
    'vue/no-v-model-argument': 'off', // 禁止使用 v-model 参数
    'no-implied-eval': 'off', // 禁止使用隐式eval
    'prefer-regex-literals': 'off', // 建议使用正则表达式字面量
    'array-callback-return': 'off', // 强制数组方法的回调函数中有 return 语句
    'vue/no-mutating-props': 'off', // 禁止修改 props
    'vue/no-template-shadow': 'off', // 禁止在模板中使用变量
    'prefer-promise-reject-errors': 'off', // 建议使用 Promise.reject
    'vue/v-on-event-hyphenation': 'off', // 事件名称
    'vue/no-multiple-template-root': 'off', // 禁止多个模板根
    'vue/attributes-order': 'off', // 属性顺序
    'no-trailing-spaces': 'off' // 禁止行尾空格
  }
};

新建文件 .prettierrc.js

module.exports = {
  printWidth: 100, // 单行输出(不折行)的(最大)长度
  tabWidth: 2, // 每个缩进级别的空格数
  useTabs: false, // 使用制表符 (tab) 缩进行而不是空格 (space)。
  semi: true, // 是否在语句末尾打印分号
  singleQuote: true, // 是否使用单引号
  quoteProps: 'as-needed', // 仅在需要时在对象属性周围添加引号
  jsxSingleQuote: false, // jsx 不使用单引号,而使用双引号
  trailingComma: 'none', // 去除对象最末尾元素跟随的逗号
  bracketSpacing: true, // 是否在对象属性添加空格
  jsxBracketSameLine: true, // 将 > 多行 JSX 元素放在最后一行的末尾,而不是单独放在下一行(不适用于自闭元素),默认false,这里选择>不另起一行
  arrowParens: 'always', // 箭头函数,只有一个参数的时候,也需要括号
  proseWrap: 'always', // 当超出print width(上面有这个参数)时就折行
  htmlWhitespaceSensitivity: 'ignore', // 指定 HTML 文件的全局空白区域敏感度, "ignore" - 空格被认为是不敏感的
  vueIndentScriptAndStyle: false, // 在VUE文件中不要缩进脚本和样式标记
  // stylelintIntegration: false,
  endOfLine: 'auto'
};

在package.json中配置

 "scripts": {
   ...
   "lint": "eslint --fix --ext .js,.ts,.vue src/**"
 }

代码验证

npm run lint  // 运行此命令可全局验证,并修复

代码规范

npx prettier -w -u .
// 期间遇到警告 [warn] Ignored unknown option { tabs: false }. 该属性改名可查看文档
stylelint 格式化代码

vscode中安装插件stylelint


image.png
npm install --save-dev stylelint stylelint-config-standard

在项目根目录下新建一个 .stylelintrc.js 文件,并输入以下内容:

module.exports = {
    extends: "stylelint-config-standard"
}

修改规则官方文档https://github.com/stylelint/stylelint/blob/5a8465770b4ec17bb1b47f359d1a17132a204a71/docs/user-guide/rules/list.md
如果你想格式化 sass scss 文件

npm i -D stylelint-scss stylelint-config-standard-scss

并将 .stylelintrc.js做修改

module.exports = {
    extends: "stylelint-config-standard-scss"
}

5、配置alias

文件vite.config.ts中

import { resolve } from 'path';
// 期间报错:找不到模块 ‘path’ 或其相对应的类型声明
// 解决方法 npm i @types/node -D
const pathResolve = (dir: string): any => {  
  return resolve(__dirname, ".", dir)          
}
export default defineConfig({
...
  resolve: {
    alias: {
      '@': resolve('src')
    }
  }
});

文件tsconfig.json中

{
  "compilerOptions": {
    ...
    "baseUrl": ".",
    "paths": {
      "@/": ["/src/*"]
    },
  },
}

6、vscode中设置vue3+ts全局代码片段

image.png

image.png

image.png

新建文件中输入设置的快捷键 v3ts即出现如下代码
image.png

"Print to console": {
       "prefix": "v3ts",  // 全局快捷键
       "body": [
               "<template>",
               "",
               "</template>",
               "",
               "<script lang='ts' setup>",
               "",
               "</script>",
               "<style lang='scss' scoped>",
               "</style>",
       ],
       "description": "Log output to console"
 }

7、安装引入element-plus

npm install element-plus --save
按需导入
npm install -D unplugin-vue-components unplugin-auto-import

vite.config.ts配置

...
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
export default defineConfig({
  plugins: [
    ...
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    })
  ]
})

8、创建路由

router/index.ts

import { App } from 'vue'
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
const routes:RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/index.vue')
  }
]
const router = createRouter({
  history: createWebHistory(),
  routes
})

export const initRouter = (app:App<Element>) => {
  return app.use(router)
}

引入路由
main.ts

import { createApp } from 'vue'
import App from './App.vue'
import {initRouter} from './router'
const app = createApp(App)
// 初始化路由
initRouter(app)
app.mount('#app')

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容