搭建vue3.2+vite+ts+pinia项目

用到的技术

vue3.2+vite+ts+pinia

搭建项目

前言

vue3+vite 会比vue2+webpack的速度快很多;Vite 是一个轻量级的、速度极快的构建工具;
vite官网

创建项目

npm create vite@latest

报错了:
初始化失败 npm ERR! Could not install from “Files\nodejs\node_cache_npx\13480“ as it does
出现问题的原因是node_cache的路径中存在空格

解决方案:
npm config set prefix D:\Program Files\nodejs\node_global
npm config set cache D:\Program Files\nodejs\node_cache

成功之后 再次执行上面的命令
需要我们输入项目名、选择的技术vue、选择的语言ts
输入之后,就成功创建了一个项目了;

按照提示 执行

npm i

运行

npm run dev

安装pinia

前言

Pinia :是新版的vuex,简化了vuex,效率更快,上手更快,推荐在vue3使用
pinia官网

安装

npm install pinia

在src下新建store文件夹,在此文件夹下新建文件即可;

在main.ts中引入

import { createPinia } from 'pinia'

const app = createApp(App);
app.use(createPinia());
app.mount('#app');

参考链接
https://www.jianshu.com/p/19de4e5556fa

安装elementplus

注意:element plus只适用于Vue3框架!

npm install element-plus --save

步骤二:在main.js中引入

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

const app = createApp(App);
app.use(ElementPlus);
app.mount('#app');

安装路由

npm install vue-router --save

新建route文件夹,新建index.ts

import { createRouter,createWebHistory,RouteRecordRaw } from "vue-router";
import { Nav } from '@/model/router';

const modules = import.meta.glob("../views/**/*.vue");

const navs: Nav[] = [
  {
    path: '/',
    name: 'demo',
    component: 'demo/Demo.vue'
  }
];

function navsToRouter (nav: Nav): RouteRecordRaw {
  return {
    ...nav,
    component: modules[`../views/${nav.component}`]
  };
}

function getRouter (): RouteRecordRaw[] {
  const routes: Array<RouteRecordRaw> = [];
  navs.map(nav => {
    return routes.push(navsToRouter(nav));
  });
  return routes
}

// 通过createRouter方法来创建一个路由 配置history模式
export default createRouter({
  routes: getRouter(),
  history:createWebHistory()
});

在main.js中引用index.js

import router from './router/index'

const app = createApp(App);
app.use(router);
app.mount('#app');

安装eslint

npm install --save-dev eslint eslint-plugin-vue

安装之后 执行

npx eslint --init

请添加图片描述
自动生成.eslintrc.cjs

rules配置文档

配置lint指令
在package.json的scripts添加指令

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

之后执行npm run lint 也可以自动修复eslint报错。

参考https://blog.csdn.net/qq_42345108/article/details/124386056

https://blog.csdn.net/weixin_39481659/article/details/127222890

安装vite-plugin-eslint包【也可以不安装】

// 该包的作用是在vite运行时自动检测eslint规范,根据配置在终端显示未通过的校验代码
npm install vite-plugin-eslint -D

安装eslint-parser 及 @babel/core 包

// 该包的作用是允许eslint在babel转换的源代码上运行
npm install @babel/eslint-parser -D

安装Prettier

执行

npm i -D prettier eslint-config-prettier eslint-plugin-prettier

自己创建文件【.prettierrc】 // 具体哪一行代表着什么可以vscode-设置-输入prettier 可以看到

{
  "printWidth": 120,
  "semi": true,
  "singleQuote": true,
  "trailingComma": "none",
  "bracketSpacing": true,
  "arrowParens": "avoid",
  "singleAttributePerLine": true,
  "quoteProps": "preserve",
  "endOfLine": "auto",
  "jsxBracketSameLine": false,
  "htmlWhitespaceSensitivity": "ignore"
}


配合eslint
https://blog.csdn.net/qq_42476927/article/details/126838755

后续可以通过 在根目录下创建 .eslintignore文件,在该文件中加入xx,忽略掉xx文件夹下的所有校验;

VSCode配置

安装ESLint及Prettier插件

打开VSCode 设置>用户>文本编辑器>格式化>勾选Format On Save
配置保存自动格式化
2. 搜索Prettier>勾选Require Config配置方案文件
3.打开VSCode设置>用户>文本编辑器>Default Formatter>选择Prettier - Code formatter配置默认格式化程序
4.ctr+shift+p打开首选项配置settings.json>添加eslint vue支持

“eslint.validate”: [
“javascript”,
“javascriptreact”,
“vue”
],

特别提醒:每次修改完Eslint及Prettier配置最好重新启动VSCode,防止出现配置不生效的情况

setting。json

	"[vue]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "editor.tabSize": 2,
    "window.zoomLevel": 0,
    "editor.accessibilityPageSize": 1,
    "workbench.colorTheme": "Monokai",
    "diffEditor.ignoreTrimWhitespace": false,
    "editor.fontSize": 15,
    "[typescript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "terminal.integrated.shell.osx": "/bin/bash",
    "powermode.enabled": true,
    "liveServer.settings.donotVerifyTags": true,
    "liveServer.settings.donotShowInfoMsg": true,
    "gitlens.views.branches.branches.layout": "list",
    "git.autofetch": true,
    "prettier.requireConfig": true,
    "editor.formatOnType": true, 
    "editor.formatOnSave": true,
    "eslint.validate": [
        "javascript",
        "javascriptreact",
        "vue"
    ],
    "editor.defaultFormatter": "esbenp.prettier-vscode"

安装sass

npm install --save-dev sass

vite.config.js

安装path

npm install --save path 

__dirname暴红 找不到名称“__dirname”
解决办法:

npm install --save-dev @types/node

import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path';
import eslintPlugin from 'vite-plugin-eslint'

// https://vitejs.dev/config/
export default defineConfig({
    // 配置前端服务地址和端口
    server: {
      hmr: true,
      // 设置反向代理,跨域
      proxy: {
        '/api': {
          target: '后端地址',
          changeOrigin: true,
        },
      },
    },
    plugins: [
      vue(), 
      eslintPlugin({
        include: ['src/**/*.js', 'src/**/*.vue', 'src/*.js', 'src/*.vue'],
        exclude: ['./node_modules/**'],
      })
    ],
    // 打包配置
    build: {
        rollupOptions: {
          // Vite 将转而去抓取这些入口点 来检测需要预构建的依赖项
            input: {
                index: path.resolve(__dirname, 'index.html'),
                login: path.resolve(__dirname, 'login.html'),
            }, output: {
                chunkFileNames: 'static/js/[name]-[hash].js',
                entryFileNames: "static/js/[name]-[hash].js",
                assetFileNames: "static/[ext]/name-[hash].[ext]"
            }
        },
        emptyOutDir: true,
    },
    // 起个别名,在引用资源时,可以用‘@/资源路径’直接访问
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
      },
    },
})

tsconfig.json

新增

	"baseUrl": "./",
    "paths": {
      "@/*": ["src/*"]
    }
{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "strict": true,
    "jsx": "preserve",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "lib": ["ESNext", "DOM"],
    "skipLibCheck": true,
    "noEmit": true,
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

补充eslintrc.cgx

module.exports = {
    'env': {
        'browser': true,
        'es2021': true
    },
    'extends': [
        'eslint:recommended', // eslint核心规则
        'plugin:vue/vue3-essential', // 继承eslint-plugin-vue组件中的基础配置
        'plugin:@typescript-eslint/recommended' // 继承eslint-plugin-prettier组件中的基础配置,
        //  安装了.prettier 的话 需要弄这个
        'plugin:prettier/recommended',
    	'eslint-config-prettier'
    ],
    'overrides': [
    ],
    "parser": "vue-eslint-parser",// 使用vue解析器
    'parserOptions': {// 设置支持的JavaScript语言选项
        'ecmaVersion': 'latest', // 指定EcmaScript的版本
        'sourceType': 'module', // script/module
        'parser': '@typescript-eslint/parser',
    },
    'plugins': [
        'vue', // eslint-plugin-vue缩写
        '@typescript-eslint''spellcheck',
        // 这个包需要安装了第7步的三个包再引入
        'prettier' // 引入规范插件  prettier <==>  eslint-plugin-prettier

    ],
    'rules': {
        'vue/multi-word-component-names': 0,
        // --以下是Possible Errors JS代码中的逻辑错误相关
        'no-console': ['error', { allow: ['debug', 'info', 'warn', 'error', 'clear'] }],
        'no-extra-parens': 'error', // 禁止不必要的括号
        'no-empty': 'error', // 禁止出现空语句块
        'no-extra-semi': 'error', // 禁止不必要的分号
        // --以下是Best Practices 最佳实践
        'dot-location': ['error', 'property'], // 要求对象的点要跟属性同一行
        'eqeqeq': 'error', // 要求使用 === 和 !==
        'no-empty-function': 'error', // 禁止出现空函数
        'no-multi-spaces': 'error', // 禁止出现多个空格
        'require-await': 'error', // 禁止使用不带await的async表达式
         // --以下是Stylistic Issues 主观的代码风格
        'brace-style': ['error', '1tbs', { 'allowSingleLine': true }], // if/elseif/else左花括号要跟if..同行,右花括号要换行;或者全部同一行
        'computed-property-spacing': 'error', // 禁止在计算属性中出现空格
        'eol-last': 'error', // 强制文件的末尾有一个空行
        'func-call-spacing': 'error', // 禁止函数名和括号之间有个空格
        'indent': ['error', 2], // 使用一致的缩进,2个空格
        'no-unneeded-ternary': 'error', // 禁止多余的三元表达式,如a === 1 ? true : false应缩写为a === 1
        'quotes': ['error', 'single'], // 要求字符串尽可能的使用单引号
        'semi': ['error', 'always'], // 要分号
        'no-shadow-restricted-names': 'error', // 禁止将标识符定义为受限的名字
        // es6
        'no-duplicate-imports': 'error', // 禁止重复导入
        'prefer-const': 'error', // 要求使用const声明不会被修改的变量
        'arrow-parens': ['error', 'as-needed'], // 箭头函数参数只有一个时,不允许写圆括号
        'arrow-spacing': 'error', // 要求箭头函数的=>前后有空格

        '@typescript-eslint/camelcase': 'off',
        '@typescript-eslint/no-this-alias': 'warn',
        '@typescript-eslint/no-var-requires': 'off',
        '@typescript-eslint/no-explicit-any': 'off',
        '@typescript-eslint/no-unused-vars': 'off',
        'linebreak-style': [
            'error',
            'unix'
        ],
        // 不同系统不同工具下换行符的问题。
        'linebreak-style': 'off',
        'spellcheck/spell-checker': [
      'warn',
      {
        skipWords: [
          // common
          'orgs',
          'http',
          'https',
          'addr',
          'whitespace',
          'diy',
          'eng',
          'autonymous',
          'www',

          // programming
          'ctor',
          'mkdir',
          'rmdir',
          'tcp',
          'udp',
          'cpu',
          'img',
          'imgs',
          'conf',
          'util',
          'utils',
          'mixin',
          'mixins',
          'sys',
          'msg',
          'func',
          'funcs',
          'validator',
          'validators',
          'identifier',
          'param',
          'params',
          'ret',
          'rets',
          'sortable',
          'asc',
          'desc',
          'auth',
          'configs',
          'todo',
          'enum',
          'iterable',
          'iterables',
          'args',
          'src',
          'dest',
          'getters',
          'proto',
          'selectable',
          'det',
          'const',
          'init',
          'del',
          'str',
          'bool',
          'ctx',
          'num',
          'len',
          'ele',
          'api',
          'formatter',
          'unknown',
          'jpeg',
          'jpg',
          'png',
          'namespacing',
          'namespaced',
          'cancelling',
          'cancelled',
          'async',
          'sdk',
          'req',
          'uri',
          'urls',
          'metadata',
          'cutboard',
          'cutboards',
          'computable',
          'chs',
          'rect',
          'timestamp',
          'prev',
          'curr',
          'uid',
          'evt',
          'kafka',
          'wss',
          'exts',
          'esc',
          'splitted',
          'svg',
          'hostname',
          'exe',
          'attrs',
          'endif',
          'debounce',
          'vod',
          'zlevel',
          'oper',
          'builtins',
          'decrypt',
          'ctrl',

          // eslint
          'uninferred',

          // web dev
          'html',
          'moz',
          'webkit',
          'dom',
          'reflow',
          'vue',
          'vuex',
          'iconfont',
          'xhr',
          'ajax',
          'wotan',
          'lodash',
          'href',
          'nav',
          'navs',
          'eslint',
          'tslint',
          'echart',
          'echarts',
          'resize',
          'scss',
          'rgb',
          'rgba',
          'polyfill',
          'typeof',
          'unshift',
          'uploader',
          'popup',
          'btn',
          'btns',
          'cascader',
          'fullscreen',
          'dropdown',
          'tooltip',
          'submenu',
          'autocomplete',
          'checkbox',
          'checkboxes',
          'date-fns',
          'decheck',
          'dechecked',
          'deselected',
          'keyup',
          'keydown',
          'mousedown',
          'mouseup',
          'mouseover',
          'mouseleave',
          'mousemove',
          'zoomend',
          'pragma',
          'whatwg',
          'unmark',
          'singleclick',
          'dblclick',
          'moveend',
          'pointermove',
          'drawstart',
          'drawend',
          'crosshair',
          'visibilitychange',
          'scroller',
          'ws', // stands for 'websocket'
          'draggable',
          'resizable',
          'viewport',
          'dasharray',
          'popups',
          'calc',
          'axios',
          'pinia'
        ],
        minLength: 3
      }
    ]
    }
};

项目打包过程中遇到报错
Top-level await is not available in the configured target environment

  1. 引入vite-plugin-top-level-await
npm install vite-plugin-top-level-await -D
  1. 在vite.config.js配置此插件
import topLevelAwait from 'vite-plugin-top-level-await'

export default defineConfig({
  plugins: [
    topLevelAwait({
      // The export name of top-level await promise for each chunk module
      promiseExportName: '__tla',
      // The function to generate import names of top-level await promise in each chunk module
      promiseImportName: i => `__tla_${i}`
    })
  ]
});

但是添加之后 启动之后报错
failed to load config from /Users/dg2021/Desktop/all/GLST/HSR/seraphina/vite.config.ts
error when starting dev server:
Error: Cannot find module ‘node:process’

查阅之后 发现时node版本太低导致的 当时使用的node版本是v14所以我进行了一下升级
执行命令

1.清除npm缓存:

npm cache clean -f

2.安装node版本管理工具n:

sudo npm install n -g

3.查看所有node版本:


npm view node versions

4.指定安装版本:

n 16.0.0

5.也可以升级到最新的稳定版本:

sudo n stable
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值