vuejs / composition-api

Composition API plugin for Vue 2
https://composition-api.vuejs.org/
MIT License
4.19k stars 342 forks source link

客户端使用vuecli 打包出来的commonjs模式的库,出现“Error: [vue-composition-api] must call Vue.use(VueCompositionAPI) before using any functio” #987

Closed linzhe141 closed 1 year ago

linzhe141 commented 1 year ago

客户端

报错vue.runtime.esm.js:619 [Vue warn]: Error in data(): "Error: [vue-composition-api] must call Vue.use(VueCompositionAPI) before using any function."

我排查了下好像是因为库文件和客户端使用的入口不一样导致这个问题的,客户端使用mjs,库使用commonjs image

但是我把main.js 修改成const VueCompositionAPI = require("@vue/composition-api");,这样确实不会报Error: [vue-composition-api] must call Vue.use(错误了 但是composition-api就会报错TypeError: Cannot read properties of undefined (reading 'text')"

linzhe141 commented 1 year ago

尝试用vite构建了一个es的包,可以正常使用

// vite.config.js
import { defineConfig } from "vite";
import { createVuePlugin } from "vite-plugin-vue2";
import { resolve } from "path";
export default defineConfig({
  build: {
    lib: {
      entry: "./src/index.js",
    },
    minify: false,
    rollupOptions: {
      external: ["@vue/composition-api"],
      output: [
        {
          format: "es",
          dir: resolve(__dirname, "./dist/es"),
        },
      ],
    },
  },
  plugins: [createVuePlugin(/* options */)],
});
linzhe141 commented 1 year ago

解决方案

在客户端使用alias将@vue/composition-api,都统一成commonjs模块,就可以正常使用了

 configureWebpack: {
    resolve: {
      alias: {
        "@vue/composition-api": path.join(
          __dirname,
          "./node_modules/@vue/composition-api/index.js"
        ),
      },
    },
  },