新建项目

执行以下语句,构建一个 Vite + Vue 项目,用时1.886秒。

npm init vite@latest my-vue-app --template vue
cd my-vue-app
npm install
npm run dev

运行npm run dev ,浏览器打开地址127.0.0.1:5173 ,控制台报错

Uncaught ReferenceError: globalThis is not defined at overlay.ts:140

打开项目,找到Vite 项目的入口文件index.html,加入以下脚本语句

<script> this.globalThis || (this.globalThis = this) </script>

则Vite + Vue项目正常运行。

项目文件与结构目录展示

Package.json文件

{
  "name": "my-vue-app",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "vue": "^3.2.45"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^4.0.0",
    "vite": "^4.0.0"
  }
}

Vite.config.js文件

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
})

目录结构

my-vue-app
	.vscode
		extensions.json
	node_modules
	public
		vite.svg
	src
		assets
			vue.svg
		components
			HelloWorld.vue
		App.vue
		main.js
		style.css
	.gitignore
	index.html
	package-lock.json
	package.json
	README.md
	vite.config.js

环境配置

多环境配置:dev、uat、prod。配置打包与开发环境等。在package.json文件中加入一下scripts 命令

"dev:dev": "vite --mode dev",
"build:uat": "vite build --mode uat",
"build:prod": "vite build --mode prod",

文件完整展示如下

"scripts": {
  "dev": "yarn dev:dev",
  "dev:dev": "vite --mode dev",
  "build": "vite build",
  "build:uat": "vite build --mode uat",
  "build:prod": "vite build --mode prod",
  "preview": "vite preview"
},

Vite 使用 dotenv环境文件目录 中加载环境文件,可以通过配置 envDir 属性指定环境文件目录。在项目根目录下创建目录 env,用于存放所有的环境文件。

在 Vite.config.js 中添加 envDir 属性指定环境文件目录为 env

envDir: path.resolve(__dirname, './env')

并在env文件夹中创建环境文件.env.env.dev.env.uat.env.prod

// 在.env中配置全局属性
VITE_BASE_API=/api
VITE_APP_NAME='demo app'
DEMO_STR=hello

// 在.env.dev中配置,仅在运行买了中含带相关-mode时有效,对应模式中的相同变量会覆盖.env中的变量(以下同)
VITE_BASE_API=/dev-api

// 在.env.uat中配置
VITE_BASE_API=/uat-api

// 在.env.prod中配置
VITE_BASE_API=/prod-api

PS:

1 无论是哪种模式,.env 文件都会被加载;
2 如果 .env.[mode] 和 .env 中有相同的 key,对应模式的环境文件中的值会覆盖 .env 对应 key 的值;
3 环境变量需要以 VITE_ 开头才会暴露到 import.meta.env 中。
4 .env.[mode].local 优先级最高,其中模式中含.local的优先级高于同级

运行项目,指定Vite.config.js文件报错,在文件中引用import path from 'path'

error when starting dev server:
ReferenceError: path is not defined

通过在main.js中配置import.meta.env 实现全局变量

import.meta.env.USER_NAME = "Yu"

JSX使用

在Vite.config.js文件中配置esbuild开启JSX的使用。

[esbuild:https://esbuild.github.io/content-types/#jsx]

esbuild: { // 使用 JSX
    jsxFactory: 'h',
    jsxFragment: 'Fragment',
    // 使用JSX 注入 helper,避免手动导入
    // jsxInject: `import React from 'react'` 
}

样式处理器

使用.scss,.sass,.less,.styl和 .stylus,必须安装相应的预处理器依赖

# .scss and .sass
npm install -D sass

# .less
npm install -D less

# .styl and .stylus
npm install -D stylus

其他资源

静态资源处理 [https://vitejs.cn/guide/assets.html#new-url-url-import-meta-url]

图片:import imgUrl from './img.png'

项目中public为静态资源文件夹,存放无需处理的文件。

兼容传统浏览器

npm i -D @vitejs/plugin-legacy

安装依赖后,在Vite.config.js文件中引用和配置

引用:import legacy from '@vitejs/plugin-legacy'
配置:plugins: [
    legacy({
      targets: ['defaults', 'not IE 11']
    })
]

插件执行排序和按需,如下例

import image from '@rollup/plugin-image'
export default defineConfig({
  plugins: [
    {
      ...image(),
      enforce: 'pre' // 在 Vite 核心插件之前调用该插件
      enforce: 'post' // 在 Vite 构建插件之后调用该插件
      apply: 'build' // 仅在build模式被调用
    }
  ]
})

项目入口设置

项目多入口页面运用,如下

├── package.json
├── vite.config.js
├── index.html
├── main.js
└── nested
    ├── index.html
    └── nested.js

则需在Vite.config.js文件中配置入口页,运行后浏览器访问http://localhost:8080/second/home.html 即可。

const { resolve } = require('path')
const { defineConfig } = require('vite')

module.exports = defineConfig({
  build: {
    rollupOptions: {
      input: {
        main: resolve(__dirname, 'index.html'),
        nested: resolve(__dirname, 'nested/index.html')
      }
    }
  }
})

相关问题

出现ES2010 运算符不支持情况,百度结果要求安装相关依赖并在.babelrc中配置plugins,在此项目中无效。

"@babel/plugin-proposal-nullish-coalescing-operator": "^7.18.6", // ??
"@babel/plugin-proposal-optional-chaining": "^7.20.7", // ?.
"babel-plugin-transform-object-rest-spread": "^6.26.0", // ...

"plugins":[
    "transform-object-rest-spread",
    "@babel/plugin-proposal-optional-chaining",  //可选链 ?.
    "@babel/plugin-proposal-nullish-coalescing-operator"  //空值合并 ??
]
Vite配置相关文献

https://juejin.cn/post/7170843707217412126

// vite.config.js
import { defineConfig } from 'vite' // 使用 defineConfig 工具函数获取类型提示:
import vue from '@vitejs/plugin-vue'
import { viteMockServe } from 'vite-plugin-mock'

export default defineConfig({
  base: '/foo/', // 开发或生产环境服务的公共基础路径
  optimizeDeps: {
    force: true // 强制进行依赖预构建
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@import '/src/assets/styles/variables.scss';` // 引入全局变量文件
      }
    },
    postcss: {
      plugins: [
        // viewport 布局适配
        postcssPxToViewport({
          viewportWidth: 375
        })
      ]
    }
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src') // 路径别名
    },
    extensions: ['.js', '.ts', '.json'] // 导入时想要省略的扩展名列表
  },
  server: {
    host: true, // 监听所有地址
    proxy: {
      // 字符串简写写法
      '/foo': 'http://localhost:4567',
      // 选项写法
      '/api': {
        target: 'http://jsonplaceholder.typicode.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      },
      // 正则表达式写法
      '^/fallback/.*': {
        target: 'http://jsonplaceholder.typicode.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/fallback/, '')
      },
      // 使用 proxy 实例
      '/api': {
        target: 'http://jsonplaceholder.typicode.com',
        changeOrigin: true,
        configure: (proxy, options) => {
          // proxy 是 'http-proxy' 的实例
        }
      },
      // Proxying websockets or socket.io
      '/socket.io': {
        target: 'ws://localhost:3000',
        ws: true
      }
    }
  },
  build: {
    outDir: 'build', // 打包文件的输出目录
    assetsDir: 'static', // 静态资源的存放目录
    assetsInlineLimit: 4096 // 图片转 base64 编码的阈值
  },
  plugins: [
    vue(),
    viteMockServe()
  ]
})

参考文献:[https://zhuanlan.zhihu.com/p/571017133]

posted on 2023-04-05 16:50  羽丫头不乖  阅读(209)  评论(0编辑  收藏  举报