[英]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 .我正在使用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.
该库以 Vue 2 为目标,但使用Vue 2 组合 API以便在时机成熟时更容易移植到 Vue 3。
After publishing the library to npm, I created a blank Vue 2 project using Vue CLI (targeting Vue 2 with TypeScript enabled).将库发布到 npm 后,我使用 Vue CLI 创建了一个空白的 Vue 2 项目(以启用 TypeScript 的 Vue 2 为目标)。
npm install <my_package>
npm install @vue/composition-api
In main.ts
I installed the Composition API as a plugin.在
main.ts
,我将 Composition API 安装为插件。
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.然后,在
App.vue
中,我从库中导入了一个组件进行测试。
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"
data() 中的错误:“TypeError:无法读取 null 的属性 'config'”
Removing Vue.use(VueCompositionApi)
from main.ts
gets rid of the error but then the component doesn't load.从
main.ts
中删除Vue.use(VueCompositionApi)
可以消除错误,但不会加载组件。 So it seems the issue is my component isn't properly registering that the Composition API exists.所以看来问题是我的组件没有正确注册组合 API 的存在。
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.在
build/rollup.config.js
搜索const external
并将@vue/composition-api
添加到列表中。
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.然后只需构建,发布到 npm,npm 更新使用包的项目中的包,它应该可以正常工作。
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.感谢Github 上的这篇文章,它引导我使用
external
配置和这个示例rollup.config.js
,指向该文章的链接准确地显示了它应该去的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.