用vite2+vue3+TypeScript4+elementPlus做一个后台管理系统

4,696 阅读4分钟

祖师爷vite已经更新到2.0版本了,一直还没玩过,这几天自己用vite2.0、vue3.0、typescript搭建了一个简易后台管理系统

直接上手操作搞一波

一、开始搭建基础的模板

使用npm命令:npm init @vitejs/app

输入项目名称

image.png

选择vue-ts模板

image.png

二、跳转到package.json目录下安装相关的包

输入命令: yarn 或者 cnpm i 或者 npm i

三、项目文件夹一览

node_modules ---依赖文件夹

public ---公共文件夹

src ---项目主要文件夹

.gitignore ---排除git提交配置文件

index.html ---入口文件

package.json ---模块描述文件

tsconfig.json ---ts配置文件

vite.config.ts ---vite配置文件

src文件夹一览

assets ---静态文件夹

components ---组件文件夹

App.vue ---页面文件

main.ts ---项目入口文件

shims-vue.d.ts ---类型定义文件(描述文件)

四、为vite创建别名

打开vite.config.ts文件,加入下面代码:

const { resolve } = require('path')

resolve:{ alias: {'@': resolve(__dirname, 'src')}}

image.png

五、配置tsconfig.json

{
  "compilerOptions": {
    // 允许从没有设置默认导出的模块中默认导入。这并不影响代码的输出,仅为了类型检查。
    "allowSyntheticDefaultImports": true,
    
    // 解析非相对模块名的基准目录
    "baseUrl": ".",

    "esModuleInterop": true,

    // 从 tslib 导入辅助工具函数(比如 __extends, __rest等)
    "importHelpers": true,

    // 指定生成哪个模块系统代码
    "module": "esnext",

    // 决定如何处理模块。
    "moduleResolution": "node",

    // 启用所有严格类型检查选项。
    // 启用 --strict相当于启用 --noImplicitAny, --noImplicitThis, --alwaysStrict, 
    // --strictNullChecks和 --strictFunctionTypes和--strictPropertyInitialization。
    "strict": true,

    // 生成相应的 .map文件。
    "sourceMap": true,

    // 忽略所有的声明文件( *.d.ts)的类型检查。
    "skipLibCheck": true,

    // 指定ECMAScript目标版本 
    "target": "esnext",
    
    // 要包含的类型声明文件名列表
    "types": [

    ],

    "isolatedModules": true,

    // 模块名到基于 baseUrl的路径映射的列表。
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    // 编译过程中需要引入的库文件的列表。
    "lib": [
      "ESNext",
      "DOM",
      "DOM.Iterable",
      "ScriptHost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

六、改造App.vue

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script lang="ts">
import { onMounted } from 'vue'

export default {
  setup() { }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}
</style>

七、安装eslint

输入命令:yarn add --dev eslint prettier eslint-config-prettier eslint-plugin-prettier eslint-plugin-vue @typescript-eslint/parser @typescr ipt-eslint/eslint-plugin

在根目录下创建 eslint 配置文件:.eslintrc.js

module.exports = {
	parser: 'vue-eslint-parser',
	parserOptions: {
		parser: '@typescript-eslint/parser',
		ecmaVersion: 2020,
		sourceType: 'module',
		ecmaFeatures: {
			jsx: true
		}
	},
	extends: [
		'plugin:vue/vue3-recommended',
		'plugin:@typescript-eslint/recommended',
		'prettier/@typescript-eslint',
		'plugin:prettier/recommended'
	],
	rules: {
		'@typescript-eslint/ban-ts-ignore': 'off',
		'@typescript-eslint/explicit-function-return-type': 'off',
		'@typescript-eslint/no-explicit-any': 'off',
		'@typescript-eslint/no-var-requires': 'off',
		'@typescript-eslint/no-empty-function': 'off',
		'vue/custom-event-name-casing': 'off',
		'no-use-before-define': 'off',
		// 'no-use-before-define': [
		//   'error',
		//   {
		//     functions: false,
		//     classes: true,
		//   },
		// ],
		'@typescript-eslint/no-use-before-define': 'off',
		// '@typescript-eslint/no-use-before-define': [
		//   'error',
		//   {
		//     functions: false,
		//     classes: true,
		//   },
		// ],
		'@typescript-eslint/ban-ts-comment': 'off',
		'@typescript-eslint/ban-types': 'off',
		'@typescript-eslint/no-non-null-assertion': 'off',
		'@typescript-eslint/explicit-module-boundary-types': 'off',
		'@typescript-eslint/no-unused-vars': [
			'error',
			{
				argsIgnorePattern: '^h$',
				varsIgnorePattern: '^h$'
			}
		],
		'no-unused-vars': [
			'error',
			{
				argsIgnorePattern: '^h$',
				varsIgnorePattern: '^h$'
			}
		],
		'space-before-function-paren': 'off',
		quotes: ['error', 'single'],
		'comma-dangle': ['error', 'never']
	}
};

创建prettier.config.js

module.exports = {
  printWidth: 100,
  tabWidth: 2,
  useTabs: false,
  semi: false, // 未尾逗号
  vueIndentScriptAndStyle: true,
  singleQuote: true, // 单引号
  quoteProps: 'as-needed',
  bracketSpacing: true,
  trailingComma: 'none', // 未尾分号
  jsxBracketSameLine: false,
  jsxSingleQuote: false,
  arrowParens: 'always',
  insertPragma: false,
  requirePragma: false,
  proseWrap: 'never',
  htmlWhitespaceSensitivity: 'strict',
  endOfLine: 'lf'
}

八、安装vue-router4

输入命令:npm install vue-router@4 --save

在src下创建router文件夹,在里面创建index.ts文件。

import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";

const container = () => import('@/pages/container/container.vue');
const login = () => import('@/pages/login/login.vue');

const routes: Array<RouteRecordRaw> = [
	{ path: '', redirect: '/login' },
	{
		path: '/',
		component: container,
		children: []
	},
	{
		path: '/login',
		name: '登录',
		component: login
	}
]

const router = createRouter({
	history: createWebHistory(),
	routes
})

export default router

在main.ts中引入

image.png

九、安装vuex

输入命令:npm install vuex@next --save

在src下创建store文件夹,在里面创建index.ts、getters.ts、mutations.ts、actions.ts文件。

index.ts

import { createStore } from "vuex";
import getters from "./getters";
import mutations from "./mutations";
import actions from "./actions";

export default createStore({
	state: {
		userInfo: JSON.parse(localStorage.getItem("userInfo") as string) || {}
	},
	getters,
	mutations,
	actions,
})

在main.ts中引入

image.png

十、安装element-plus

输入命令:npm install element-plus --save

我这里采用完全引入的方式:

image.png

也可以根据项目需要按需引入:

首先输入命令:npm install vite-plugin-style-import -D

然后,将 vite.config.js 修改为:

引入 .scss 样式:

请确保已经安装了 sass 依赖并将 element-plus/packages/theme-chalk/src/base.scss 文件在入口文件中引入

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import styleImport from 'vite-plugin-style-import'

export default defineConfig({
  plugins: [
    vue(),
    styleImport({
      libs: [{
        libraryName: 'element-plus',
        esModule: true,
        ensureStyleFile: true,
        resolveStyle: (name) => {
          name = name.slice(3)
          return `element-plus/packages/theme-chalk/src/${name}.scss`;
        },
        resolveComponent: (name) => {
          return `element-plus/lib/${name}`;
        },
      }]
    })
  ]
})

引入 .css 样式

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import styleImport from 'vite-plugin-style-import'

export default defineConfig({
  plugins: [
    vue(),
    styleImport({
      libs: [
        {
          libraryName: 'element-plus',
          esModule: true,
          ensureStyleFile: true,
          resolveStyle: (name) => {
            return `element-plus/lib/theme-chalk/${name}.css`;
          },
          resolveComponent: (name) => {
            return `element-plus/lib/${name}`;
          },
        }
      ]
    })
  ]
})

结论

前期的准备工作就到这里结束了,后续就是搭建侧边栏和登录界面了。后台管理系统的基础架构我已初步搭建完毕,已放置我的GitHub仓库,欢迎兄弟们给个start。后续的功能还在开发中,敬请期待。

附上仓库地址:github.com/wuguanfei/v…

image.png