vite2.0配置学习(typescript版本)

2,501 阅读2分钟

介绍

  • 尤于溪的原话。
  • vite Vue CLI 类似,vite 也是一个提供基本项目脚手架和开发服务器的构建工具。
  • vite基于浏览器原生ES imports的开发服务器。跳过打包这个概念,服务端按需编译返回。
  • vite速度比webpack10+倍,支持热跟新, 但是出于处于测试阶段。
  • 配置文件也支持热跟新!!!

创建

执行npm init @vitejs/app ,我这里选择的是vue-ts

版本

"vite": "^2.0.0-beta.48"

alias别名

vite.config.ts

const path = require('path')
  alias: {
    "@": path.resolve(__dirname, "src"),
    "@c": path.resolve(__dirname, "src/components")
  },

环境变量配置

1、在根目录创建

2、只有前缀为的变量VITE_才对Vite处理的代码公开。一以下为.env.production文件,其它类似。 shell # 开发环境 VITE_APP_ENV = 'development' # api 地址 VITE_APP_PATH = 'dev/...'

3、启动文件package.json,在命令后面加上--mode test就好了,这个跟vue2一样

"dev:test": "vite --mode test",
import.meta.env 进行获取变量

4、使用,跟vue2有些区别,在vite.config.ts内读取不到,其它文件可以拿到

在vite.config.ts内拿到代码,引入loadEnv

import { defineConfig, loadEnv } from 'vite'
export default ({ mode }) =>{
  const env=loadEnv(mode, process.cwd());  // 获取.env文件里定义的环境变量
  // console.log(12, env)
  return defineConfig({
   // ...
  })
}

输出为:

添加vue-router(vue3使用4.0+版本)

1、安装 npm i vue-router@4.0.2 --save,安装4.0版本

2、index.ts

import {createRouter, createWebHashHistory, RouteRecordRaw} from 'vue-router'
// @ts-ignore
const test = () => import('../views/test1.vue')
const routes: Array<RouteRecordRaw> = [
    {path: "/", redirect: "/test1"},
    {
        path: "/test1",
        name: 'test1',
        component: test,
    }
]
const router = createRouter({
    history: createWebHashHistory(),
    routes: routes
})

export default router

3、 main.ts

import router from "./router"
createApp(App)
    .use(router)
    .mount('#app')

添加vuex(版本同样要4以上)

1、安装 npm i vuex@index -D

2、store/index.ts

import { createStore } from 'vuex'

export default createStore({
  state: {
  },
  //...
})

3、main.ts

import store from './store'

createApp(App)
    .use(store)
    .mount('#app')

scss环境

1、安装npm i sass -D,可以直接使用sass语法了
2、vite.config.ts,全局引入scss文件

css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@import "./src/assets/scss/global.scss";`//你的scss文件路径
      }
    }
  },