1 概述
環境Vue3
+Vite
,需要引入ECharts
庫。
2 嘗試
目前ECharts
已更新到5.0
版本,在Vue
中引入並不難,npm
/cnpm
安裝后在需要的組件中引入:
import echarts from 'echarts'
即可。
但,
問題是這是以前的版本可行的,更新到5.0
版本后需要使用其他方法。
另一方面官方文檔是使用require
引入:
但是,這是在Webpack
的情況下,在Vite
中並不能直接使用require
,官方issue
有討論,明說了require
不支持,這是一個Node
的特性,建議使用import
:
3 解決方案
先安裝:
npm install --save echarts
#或
cnpm install --save echarts
安裝后在需要使用的組件中使用import
引入:
import * as echarts from 'echarts'
...
mounted(){
var myChart = echarts.init(document.getElementById('main'))
//...
}
這樣就能正常使用了。
最重要的就是將以前的
import echarts from 'echarts'
改為
import * as echarts from 'echarts'