欢迎访问 生活随笔!

凯发ag旗舰厅登录网址下载

当前位置: 凯发ag旗舰厅登录网址下载 > 前端技术 > vue >内容正文

vue

推荐一个 vue3 全家桶 ts vite2 element-凯发ag旗舰厅登录网址下载

发布时间:2025/1/21 vue 20 豆豆
凯发ag旗舰厅登录网址下载 收集整理的这篇文章主要介绍了 推荐一个 vue3 全家桶 ts vite2 element-plus 的网站实战项目 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

五一期间,花了 3 天时间,边学 vue3 和 vite2,边重构自己的项目,终于都用 vue3 typescript vite2 vuex4 vue-router4 element-plus 重构完啦!

终于完成一项心心念念的 2021 年度目标了 ✌️

项目地址:

https://github.com/biaochenxuying/blog-vue-typescript

效果

效果图:

  • pc 端

  • 移动端

完整效果请看:

https://biaochenxuying.cn

功能

已经完成功能

  • [x] 登录

  • [x] 注册

  • [x] 文章列表

  • [x] 文章归档

  • [x] 标签

  • [x] 关于

  • [x] 点赞与评论

  • [x] 留言

  • [x] 历程

  • [x] 文章详情(支持代码语法高亮)

  • [x] 文章详情目录

  • [x] 移动端适配

  • [x] github 授权登录

前端主要技术

所有技术都是当前最新的。

  • vue:^3.0.5

  • typescript : ^4.1.3

  • element-plus: ^1.0.2-beta.41

  • vue-router : ^4.0.6

  • vite: ^2.2.3

  • vuex: ^4.0.0

  • axios: ^0.21.1

  • highlight.js: ^10.7.2

  • marked:^2.0.3

1. 初化化项目

用 vite-app 创建项目

yarn create vite-app # 或者 npm init vite-app 

然后按照提示操作即可!

进入项目,安装依赖

cd yarn # 或 npm i

运行项目

yarn dev 

打开浏览器 http://localhost:3000 查看

2. 引入 typescript

在创建项目的时候可以 typescript 的,如果你选择了 typescript ,可以忽略第 2 个步骤。

加入 ts 依赖

yarn add --dev typescript

在 项目根目录下创建 typescript 的配置文件 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"] }

在 src 目录下新加 shim.d.ts 文件

/* eslint-disable */ import type { definecomponent } from 'vue'declare module '*.vue' {const component: definecomponent<{}, {}, any>export default component }

把 main.js 修改成 main.ts

在根目录,打开 index.html

修改为:

3. 引入 eslint

安装 eslint prettier 依赖

@typescript-eslint/parser @typescr ipt-eslint/eslint-plugin 为 eslint 对 typescript 支持。

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

4. vue-router、vuex

npm install vue-router@4 vuex

4.1 vuex

在根目录下创建 store/index.ts

import { injectionkey } from 'vue' import { createstore, store } from 'vuex'export interface state {count: number }export const key: injectionkey> = symbol()export const store = createstore({state() {return {count: 0}},mutations: {increment(state) {state.count }} })

main.ts 修改

import { createapp } from 'vue' import { store, key } from './store' import app from './app' import './index.css'const app = createapp(app)app.use(store, key)app.mount('#app')

components/helloword.vue 修改

4.2 vue-router

在 src 目录下建立 router/index.ts,内容如下:

import { createrouter, createwebhistory, routerecordraw } from "vue-router"; import helloworld from "../components/helloworld.vue";const routes: array = [{path: "/",name: "helloworld",component: helloworld,},{path: "/about",name: "about",// route level code-splitting// this generates a separate chunk (about.[hash].js) for this route// which is lazy-loaded when the route is visited.component: () =>import(/* webpackchunkname: "about" */ "../components/about.vue")} ];const router = createrouter({history: createwebhistory(process.env.base_url),routes, });export default router;

再新建一个 components/about.vue 文件,内容如下:

import { definecomponent } from 'vue'export default definecomponent({name: 'about',data() {return {msg: 'hello vue 3.0   vite!'}},setup() {} })

再修改 main.ts

import { createapp } from 'vue' import { store, key } from './store' import router from "./router"; import app from './app' import './index.css'const app = createapp(app)app.use(store, key) app.use(router) app.mount('#app')

再访问 http://localhost:3000/

和 http://localhost:3000/about 即可

5. 加入 element plus

5.1 安装 element-plus

全局安装

npm install element-plus --save

5.2 引入 element plus

你可以引入整个 element plus,或是根据需要仅引入部分组件。我们先介绍如何引入完整的 element。

完整引入

在 main.js 中写入以下内容:

import { createapp } from 'vue' import elementplus from 'element-plus'; import router from "./router"; import 'element-plus/lib/theme-chalk/index.css'; import app from './app.vue'; import './index.css'const app = createapp(app) app.use(elementplus) app.use(router) app.mount('#app')

以上代码便完成了 element plus 的引入。需要注意的是,样式文件需要单独引入。


按需引入

借助 babel-plugin-component,我们可以只引入需要的组件,以达到减小项目体积的目的。

首先,安装 babel-plugin-component:

npm install babel-plugin-component -d

然后,将 .babelrc 修改为:

{"plugins": [["component",{"libraryname": "element-plus","stylelibraryname": "theme-chalk"}]] }

接下来,如果你只希望引入部分组件,比如 button 和 select,那么需要在 main.js 中写入以下内容:

import { createapp } from 'vue' import { store, key } from './store'; import router from "./router"; import { elbutton, elselect } from 'element-plus'; import app from './app.vue'; import './index.css'const app = createapp(app) app.component(elbutton.name, elbutton); app.component(elselect.name, elselect);/* or* app.use(elbutton)* app.use(elselect)*/app.use(store, key) app.use(router) app.mount('#app') app.mount('#app')

更详细的安装方法请看 快速上手。

5.3 全局配置

在引入 element plus 时,可以传入一个全局配置对象。

该对象目前支持 size 与 zindex 字段。size 用于改变组件的默认尺寸,zindex 设置弹框的初始 z-index(默认值:2000)。按照引入 element plus 的方式,具体操作如下:

完整引入 element:

import { createapp } from 'vue' import elementplus from 'element-plus'; import app from './app.vue';const app = createapp(app) app.use(elementplus, { size: 'small', zindex: 3000 });

按需引入 element:

import { createapp } from 'vue' import { elbutton } from 'element-plus'; import app from './app.vue';const app = createapp(app) app.config.globalproperties.$element = option app.use(elbutton);

按照以上设置,项目中所有拥有 size 属性的组件的默认尺寸均为 'small',弹框的初始 z-index 为 3000。

5.4 配置 vite.config.ts

其中 proxy 和 alias 是和 vue-cli 区别比较大的地方。

import { defineconfig } from 'vite' import vue from '@vitejs/plugin-vue' import styleimport from 'vite-plugin-style-import' import path from 'path'// https://vitejs.dev/config/ 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}`;},}]})],/*** 在生产中服务时的基本公共路径。* @default '/'*/base: './',/*** 与“根”相关的目录,构建输出将放在其中。如果目录存在,它将在构建之前被删除。* @default 'dist'*/// outdir: 'dist',server: {// hostname: '0.0.0.0',host: "localhost",port: 3001,// // 是否自动在浏览器打开// open: true,// // 是否开启 https// https: false,// // 服务端渲染// ssr: false,proxy: {'/api': {target: 'http://localhost:3333/',changeorigin: true,ws: true,rewrite: (pathstr) => pathstr.replace('/api', '')},},},resolve: {// 导入文件夹别名alias: {'@': path.resolve(__dirname, './src'),views: path.resolve(__dirname, './src/views'),components: path.resolve(__dirname, './src/components'),utils: path.resolve(__dirname, './src/utils'),less: path.resolve(__dirname, "./src/less"),assets: path.resolve(__dirname, "./src/assets"),com: path.resolve(__dirname, "./src/components"),store: path.resolve(__dirname, "./src/store"),mixins: path.resolve(__dirname, "./src/mixins")},} })

踩到坑

在 npm run dev 打包时不报错,但是在 npm run build 时却报错了,build 的时候会把 node_modules 里面的文件也编译,所以挺多 element-plus 的类型文件报错了。

把 tsconfig.json 里面的 include 和 exclude 修改一下就不会了,配置如下

{"compileroptions": {"target": "esnext","module": "esnext","moduleresolution": "node","strict": true,"jsx": "preserve","sourcemap": true,// 忽略 this 的类型检查, raise error on this expressions with an implied any type."noimplicitthis": false,"resolvejsonmodule": true,"esmoduleinterop": true,"lib": ["esnext", "dom"],"types": ["vite/client"]},"include": ["/src/**/*.ts", "/src/**/*.d.ts", "/src/**/*.tsx", "/src/**/*.vue"],// ts 排除的文件"exclude": ["node_modules"] }

vue3 vite2 打包出来的文件和原来 vue2 版的差别也挺大的,由原来 2.5m 直接变成了 1.8m ,amazing!

最后

项目代码大多都是 2 年前的,还有很多可以优化的地方,这次重构的过程没对原来的样式和代码做什么改动,没那么多时间,加上我懒 ????

这次就升级了主要框架与相应的 ui 库,过了一遍 vue3 中的 api,发现很多 vue3 中新的 api 都用不上,主要是要熟练一下 vue3 和 vite2 项目搭建,这假期也算有所收获。

具体项目源码请看:

https://github.com/biaochenxuying/blog-vue-typescript

至此,一个基于 vue3 全家桶 vite2 typescript element plus 的开发环境已经搭建完毕,现在就可以编写代码了,各个组件的使用方法请参阅它们各自的文档。

不得不说 vue3 element plus vite typescript 是真的香!

推荐一个 vue3 相关的资料汇总:vue3 的学习教程汇总、源码解释项目、支持的 ui 组件库、优质实战项目,相信你会挖到矿哦!

推荐阅读

  • typescript 中提升幸福感的 10 个高级技巧

总结

以上是凯发ag旗舰厅登录网址下载为你收集整理的推荐一个 vue3 全家桶 ts vite2 element-plus 的网站实战项目的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得凯发ag旗舰厅登录网址下载网站内容还不错,欢迎将凯发ag旗舰厅登录网址下载推荐给好友。

网站地图