Skip to content

在 Vue 项目中引入第三方 CDN 库

1. 在组件中引入

由于 <template> 中不能使用 <script> 标签,所以我们需要使用 <component> 组件来引入。

vue
<template>
  <component is="script" src="https://unpkg.com/function-plot/dist/function-plot.js"></component>
</template>

2. 全局使用

如果我们希望在全局使用,例如使用 functionPlot 函数,我们可以使用 vite-plugin-externals 插件来将其作为外部库。

安装 vite-plugin-externals 插件:

bash
pnpm add -D vite-plugin-externals

vite.config.ts 中配置:

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    viteExternalsPlugin({
      externals: [
        {
          module: 'function-plot',
          global: 'functionPlot'
        }
      ]
    })
  ]
})

如果你在开发环境中引入了生产环境的库,可能会使得 HMR 失败。

你也可以使用 disableInServe: true 避免在 Serve 模式中转换,参见文档