Vue 3 - 不支持 "highcharts" 的动态要求

Vue 3 - Dynamic require of "highcharts" is not supported

我正在尝试像这样包含 highcharts-vue:

import { createApp } from 'vue'
import { createPinia } from 'pinia'

import App from './App.vue'
import router from './router'

import HighchartsVue from "highcharts-vue";


const app = createApp(App)

app.use(createPinia())
app.use(router)

app.use(HighchartsVue);

app.mount('#app')

但我收到错误消息:

 Dynamic require of "highcharts" is not supported

package.json

{
  "name": "mwc-web",
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview --port 5050"
  },
  "dependencies": {
    "@popperjs/core": "^2.11.4",
    "bootstrap": "^5.1.3",
    "bootstrap-vue-3": "^0.1.9",
    "highcharts": "^10.0.0",
    "highcharts-vue": "^1.4.0",
    "moment": "^2.29.1",
    "pinia": "^2.0.11",
    "vue": "^3.2.31",
    "vue-router": "^4.0.12"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^2.2.2",
    "@vue/cli-plugin-babel": "^5.0.4",
    "sass": "^1.49.9",
    "sass-loader": "^12.6.0",
    "vite": "^2.8.4"
  }
}

vite.config.js

import { fileURLToPath, URL } from 'url'

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  optimizeDeps: {
    exclude: ['highcharts'],
  }
})

babel.config.js

module.exports = {
    presets: [
      '@vue/cli-plugin-babel/preset'
    ]
}

这是 vue3 + highcharts-vue 的工作示例:https://codesandbox.io/s/vue3-highcharts-example-k98kyz

确保更新到最新版本,并使用 babel 或任何其他转译器来处理 ESM 包。

我认为问题的原因是这个配置:

optimizeDeps: {
  exclude: ['highcharts'], // ❌ don't do this
}

解决方案是从 optimizeDeps.exclude 中删除 highcharts

此外,使用 Vite 时不需要 Babel 配置。这可能是问题的另一个来源。

demo