vite构建vue项目

1,345 阅读2分钟

文章索引:

  • vite
  • 集成vue-router
  • 后续会加入其它的特性

vite使用

一.vite简介 Vite 是面向现代浏览器,基于原生模块系统 ESModule 实现了按需编译的 Web 开发构建工具。在生产环境下基于 Rollup 打包。 优点:

  • 快速冷启动服务器
  • 即时热模块更换(HMR)
  • 真正的按需编译

二、vite 创建项目

 // 全局安装脚手架
npm i create-vite-app -g
#or
yarn global add create-vite-app
// 创建项目 
cva [项目名]
cd <项目名>   // 进入新创建的项目
yarn     // 安装项目依赖
yarn dev // 启动项目
npm i sass -dev   // 添加sass开发依赖-需添加到devdependency中

三、vite配置 vite.config.js vite.config.js的作用类似于之前 @vue-cli 项目中的 vue.config.js

import path from 'path'
module.exports = {
  // 导入别名
  alias: {
    '/@/': path.resolve(__dirname, './src'),
    '/@/': path.resolve(__dirname, './src/views'),
    '/@components/': path.resolve(__dirname, './src/components'),
    '/@utils/': path.resolve(__dirname, './src/utils'),
  },
  // 配置Dep优化行为
  optimizeDeps: {
    include: ["lodash"]
  },
  // 为开发服务器配置自定义代理规则。
  proxy: {
    '/api': {
      target: 'http://xxx/mock/',
      changeOrigin: true,
      rewrite: (path: string) => path.replace(/^\/api/, '')
    }
  }
  // ... 
}

四、改造创建好的vite脚手架

可以在项目目录下创建需要的文件夹,将main.js改为main.ts,如遇到vscode报错可以在src目录下创建xxx.d.ts文件写入:

declare module '*.vue' {
  import {ComponentOptions} from 'vue'
  const component: ComponentOptions
  export default component
}
// 如依旧报错,可以关闭xxx.d.ts文件再打开,之后不关闭此文件,就不会报错了

vite中集成vue-router

  • tips:使用npm info vue-router versions查看所有的版本号,安装完成后就可以在项目中使用了
// 可以在src下创建router目录对路由进行管理
import halo from '@/components/HelloWorld.vue'
import {createRouter, createWebHashHistory} from 'vue-router'

const history = createWebHashHistory()
export const router = createRouter({
  history,
  routes: [
    {
      path: '/', component: halo
    }
  ]
})

//在main.ts中导入
import router from './router'
import {createApp} from 'vue'
import App from './App.vue'

const app = createApp(App)
// 此处可以写入捕获全局中的错误进行处理
// app.config.errorHandler = (message: any) => {
//   console.exception(...message);
// };
// app.config.warnHandler =
//     (message) => {
//       console.error(message+'123')
//     }
try {
  app.use(router);
} catch (e) {
  throw e;;
}
app.mount('#app')
  • 到此我们项目已经初始化完成了