uniapp vue3 引入echarts时echarts对象被编译成(void 0)如何解决?
在uniapp中使用vue3引入echarts时,遇到一个问题:echarts对象被编译成了(void 0),导致无法正常使用图表功能。具体表现为初始化图表时获取不到echarts实例,控制台报错显示"echarts is not defined"。尝试过直接import echarts from ‘echarts’,也试过按需引入,但问题依旧。请问这是什么原因导致的?应该如何解决?
2 回复
在uniapp vue3中引入echarts时,如果echarts对象被编译成(void 0),可能是因为打包时被tree-shaking优化掉了。
解决方案:
- 使用完整引入:
import * as echarts from 'echarts' - 在vite.config.js中配置:
optimizeDeps: {
include: ['echarts']
}
- 或者使用require方式动态引入
在 UniApp Vue3 中,ECharts 对象被编译成 (void 0) 通常是由于模块引入方式或编译配置问题导致的。以下是几种常见解决方案:
1. 正确引入 ECharts
确保使用正确的方式引入 ECharts:
import * as echarts from 'echarts';
2. 配置 Vue 编译器选项
在 vue.config.js 中配置编译器选项,避免 ECharts 被 Tree Shaking 优化掉:
module.exports = {
configureWebpack: {
optimization: {
usedExports: false,
},
},
};
3. 使用 require 动态引入
在组件中动态引入 ECharts:
const echarts = require('echarts');
4. 配置条件编译
在 UniApp 中,可能需要针对不同平台配置条件编译:
// #ifdef H5
import * as echarts from 'echarts';
// #endif
5. 检查 ECharts 版本兼容性
确保使用的 ECharts 版本与 UniApp Vue3 兼容,建议使用最新稳定版。
6. 完整示例代码
<template>
<view>
<canvas id="chart" style="width: 100%; height: 300px;"></canvas>
</view>
</template>
<script setup>
import { onMounted } from 'vue';
import * as echarts from 'echarts';
onMounted(() => {
const chart = echarts.init(document.getElementById('chart'));
chart.setOption({
title: { text: '示例图表' },
series: [{ type: 'bar', data: [1, 2, 3] }]
});
});
</script>
注意事项:
- 确保已正确安装 ECharts:
npm install echarts - 如果使用 TypeScript,检查
tsconfig.json配置 - 在 H5 平台测试时,可能需要额外的 DOM 操作支持
通过以上方法通常可以解决 ECharts 被编译为 (void 0) 的问题。

