美文网首页
初始化vite+vue3+ts项目

初始化vite+vue3+ts项目

作者: 新世界的冒险 | 来源:发表于2022-04-30 20:36 被阅读0次

    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')
    
    

    相关文章

      网友评论

          本文标题:初始化vite+vue3+ts项目

          本文链接:https://www.haomeiwen.com/subject/taryyrtx.html