简体   繁体   中英

Why do I get an error when I use the Vue 2 Composition API in a Vue 2 component library built with vue-sfc-rollup?

I am building a component library using vue-sfc-rollup . The library targets Vue 2 but uses the Vue 2 Composition API to make it easier to port to Vue 3 when the time comes.

After publishing the library to npm, I created a blank Vue 2 project using Vue CLI (targeting Vue 2 with TypeScript enabled).

npm install <my_package>
npm install @vue/composition-api

In main.ts I installed the Composition API as a plugin.

import Vue from 'vue'
import VueCompositionApi from '@vue/composition-api'

Vue.use(VueCompositionApi)

Then, in the App.vue I imported a component from my library to test.

import { MyComponent } from '@mypackage/components'

export default Vue.extend({
  components: {
    MyComponent,
  }
})

However, when I run this in the browser, I get the following error.

Error in data(): "TypeError: Cannot read property 'config' of null"

Removing Vue.use(VueCompositionApi) from main.ts gets rid of the error but then the component doesn't load. So it seems the issue is my component isn't properly registering that the Composition API exists.

The issue was that rollup needs to be told that the library has an external dependency.

In the build/rollup.config.js search for const external and add @vue/composition-api to the list.

const external = [
  'vue',
  '@vue/composition-api',  // <-- add this!
]

Then just build, publish to npm, npm update the package in the project consuming the package and it should work without error.

Thanks to this post on Github that steered me to the external config and this example rollup.config.js the post links to that showed exactly where it should go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM