使用Vite搭建vue3.0项目
前提:环境准备
- 第一步 node环境安装
node的下载地址:
https://nodejs.org/en/ - 第二步
下载git 并安装
git的下载地址
https://gitforwindows.org/ - 第三步
git 和node 的全局变量配置(这里不做详细的配置说明了可以参考
https://www.cnblogs.com/zhouyu2017/p/6485265.html)
1. 使用NPM安装
npm init @vitejs/app
效果如下图:
2. 安装
2.1 输入项目名称选择要创建的框架(我们选择Vue)
2.2 选择vue-ts 如下图所示
然后按回车确认
2.3 按照指示进入创建的目录结构查看
如下图所示
2.4 安装依赖
npm i
2.5 启动
npm run dev
2.6 启动成功
在浏览器里输入提示的访问地址之后,进入首页,启动成功后的界面如下
3. 安装Naive UI
3.1 使用webstrom
使用webstorm 通过点击 File -> open 选择刚创建的项目 打开, 如下图, 点击下方的Terminal, 打开控制台界面
3.2 安装Naive UI
Naive UI的官方地址
在webstrom的控制台输入一下命令进行安装:
npm i -D naive-ui
接着安装Naive UI 的字体, 命令如下:
npm i -D vfonts
3.3 新建测试文件Test
进入src/components 文件右击NEW -> file 修改文件名为Test.vue
3.4 按需引入
按需引入如图所示
3.5 将Test组件使用到首页
在app.vue中的修改如下:
3.6 查看效果
进入浏览器之前打开的界面http://localhost:3000/ 查看效果, 有按钮且样式正确的出现, 则证明简单的搭建成功, 可以在上面进行自己的Vue3.0 和NaiveUI的测试或者学习
4. 配置文件vite.config.js
项目根目录下找到vite.config.js 然后配置, 部分配置如下
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
const path = require('path');
// https://vitejs.dev/config/
export default defineConfig({
alias: {
/*
路径别名
若为文件系统路径必须是绝对路径的形式,否则将以别名原样呈现,不会解析为文件系统路径路径
*/
'@':path.resolve(__dirname, './src'),
},
plugins: [vue()],
server:{
host:'localhost',
port:3000,
open:true,
strictPort:false,//如果端口占用,是退出,还是尝试其他端口
https: false,// 是否开启 https
// 反向代理
proxy: {
// string shorthand
'/foo': 'http://localhost:3012',
// with options
'/api': {
target: 'http://james-li-test.com',
changeOrigin: true,
rewrite: (path:any) => path.replace(/^\/api/, '')
},
}
},
//生产模式打包配置
build:{
outDir: 'dist',//Specify the output directory (relative to project root).
}
})
5. 配置路由
npm install vue-router@4
src目录下新建 router文件, router文件下新建index.js 文件
文件内容如下:
import { createRouter , createWebHistory } from 'vue-router'
const routes = [
{
path : '/',
component : () => import('../components/Test.vue'),
}
]
const router = createRouter({
history : createWebHistory(process.env.BASE_URL),
routes
})
export default router
在min.ts下新增代码
完整代码如下:
import { createApp } from 'vue';
import App from './App.vue';
// @ts-ignore
import router from './router';
const app =createApp(App);
import naive from 'naive-ui';
import axios from "axios";
app.config.globalProperties.$axios = axios
app.use(naive).use(router).mount('#app')
6. 安装axios
npm install axios
在main.ts中配置axios, 具体配置如上述的main.ts完整的代码