1. 修改 vite.config.js 的配置,安装 vite 对 vue2 插件的支持
- vite 需要安装 vite4.x 版本
pnpm i vite@4.4.9 -D
pnpm i vite-plugin-vue2 -D
或
pnpm i @vitejs/plugin-vue2 -D
// import { createVuePlugin } from 'vite-plugin-vue2' // 仅支持Vue 2.6或更早版本
import vue from '@vitejs/plugin-vue2' // 只支持vue (>=2.7.0)的版本
export default {
plugins: [
// createVuePlugin(),
vue()
]
}
2. vue 与 vue-template-compiler 需要同一个版本
pnpm i vue@2.7.16 vue-template-compiler@2.7.16 -S
3. 环境变量的获取问题
- 获取环境变量的方法:
import.meta.env.VITE_APP_BASE_API
4. Echarts 局部引入报错:TypeError: Cannot read property ‘findAxisModel’ of undefined
在 Echarts 局部引入依赖的时候,如果有需要用到的依赖没有引入就会报错,比如在使用柱状图+极坐标显示环形图的时候,如果没有引入 ploar 就会出现标题的报错,这时候只要引入这个依赖就好了:
import 'echarts/lib/component/polar'
5. 引入scss全局变量文件
css: {
// CSS 预处理器
preprocessorOptions: {
// 定义全局 SCSS 变量
scss: {
javascriptEnabled: true,
additionalData: `@import "./src/styles/variables.scss";`
}
}
}
6. 使用vite官方提供的方式,获取图片的路径
/**
* 使用vite官方提供的方式,获取图片的路径
*
* @param {*} url
* @returns {*}
*/
export const getViteImageUrl = function (url) {
return new URL(`/src/assets/${url}`, import.meta.url).href
}
7. 打包报了一个错: Top-level await is not available in the configured target environment (“chrome87”, “edge88”, “es2020”, “firefox78”, “safari14”)
- 错误原因
「ECMAScript」提案 Top-level await 由 Myles Borins 提出,它可以让你在模块的最高层中使用 await 操作符。在这之前,你只能通过在 async 函数或 async generators 中使用 await 操作符。Top-level await 是个新特性,
打包不支持此特性
引入 vite-plugin-top-level-await
pnpm i vite-plugin-top-level-await -D
在 vite.config.js 配置此插件
import topLevelAwait from 'vite-plugin-top-level-await'
export default defineConfig({
plugins: [
topLevelAwait({
// The export name of top-level await promise for each chunk module
promiseExportName: '__tla',
// The function to generate import names of top-level await promise in each chunk module
promiseImportName: i => `__tla_${i}`
})
]
})