项目实战
windows环境搭建
nodeJs安装
nodeJs官网:https://nodejs.org/en,底部两个大型绿色按钮是node的版本,推荐使用左侧的(大多数人下载的),下载完成双击运行,一路下一步安装。
vite3安装+项目新建
打开cmd命令面板,cd到存放项目目录,输入 npm create vite@latest
,它问可以继续吗?,当然y加回车啦,它问项目名称,输入你需要新建的项目名称加回车确认,它问选择一个框架,这里当然选vue,它问选择一个变体,选择TypeScript加回车,恭喜你成功,你现在可以cd到你刚刚新建目录,然后安装依赖npm install
,安装完成后执行npm run dev 运行项目
配置tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"module": "ESNext",
"moduleResolution": "Node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
"lib": ["ESNext", "DOM"],
"skipLibCheck": true,
"baseUrl": "./",
"paths": {
"@/*": ["./src/*"]
},
"types": ["vite/client"]
},
"include": [
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.tsx",
"src/**/*.vue",
"./auto-imports.d.ts",
"./components.d.ts"
],
"references": [{
"path": "./tsconfig.node.json" }]
}
配置vite.config.ts
import {
defineConfig, loadEnv, UserConfigExport, ConfigEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import legacyPlugin from '@vitejs/plugin-legacy'
//按需加载
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import {
ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import ElementPlus from 'unplugin-element-plus/vite'
import {
resolve } from 'path'
import viteCompression from 'vite-plugin-compression'
const config = ({
mode }: ConfigEnv): UserConfigExport => {
const pathResolve = (dir: string): string => resolve(__dirname, '.', dir)
const isEnvProduction = mode === 'production'
const modeObj = loadEnv(mode, process.cwd())
const BaseUrl: string = modeObj['VITE_APP_BASE_API']
const ApiUrl = 'api'
return defineConfig({
plugins: [
vue(),
legacyPlugin({
targets: ['chrome 52'] // 需要兼容的目标列表,可以设置多个
}),
viteCompression({
verbose: true,
disable: false,
threshold: 10240,
//打包压缩
algorithm: 'gzip',
ext: '.gz'
}),
AutoImport({
resolvers: [ElementPlusResolver()]
}),
//组件缓存
Components({
resolvers: [ElementPlusResolver()]
}),
ElementPlus({
// options
})
],
base: './',
define: {
__VUE_I18N_LEGACY_API__: false,
__VUE_I18N_FULL_INSTALL__: false,
__INTLIFY_PROD_DEVTOOLS__: false
},
server: {
host: '0.0.0.0',
port: 9527,
open: false,
proxy: {
['/' + ApiUrl]: {
target: BaseUrl,
secure: false, // 如果是https接口,需要配置这个参数
changeOrigin: true,
rewrite: (path) => {
//代理路径处理
return path
.split('/')
.filter((item) => item)
.filter((item, index) => index > 1)
.join('/')
}
}
}
},
resolve: {
alias: [{
find: '@', replacement: pathResolve