将组件从应用程序移动到库时出错

Error while moving component from application to a library

我在 Vuetify 顶部创建组件库时遇到问题 2.x。

我创建了一个简单的导航抽屉包装器:

<template>
    <v-navigation-drawer app v-model="drawer">
        <v-list-item>
            <v-list-item-content>
                <v-list-item-title class="title">
                    Application
                </v-list-item-title>
                <v-list-item-subtitle>
                    subtext
                </v-list-item-subtitle>
            </v-list-item-content>
        </v-list-item>
    </v-navigation-drawer>
</template>

<script>
export default {
    name: 'MySidebar',
    data: () => ({
        drawer: null,
    }),
};
</script>

当这个组件被放置在我的应用程序中时,它按预期工作。但是,当同一个组件在库中时,应用程序会崩溃。

<template>
    <v-app>
        <my-sidebar/>
    </v-app>
</template>

<script>
import MySidebar from 'my-library/src/components/MySidebar.vue'; // Error
import MySidebar from './src/components/MySidebar.vue'; // Works

export default {
    name: 'App',
    components: {
        MySidebar,
    },
};
</script>

在第一次导入时,应用程序无法获取 this.$vuetify 对象,但是当我 console.log(this.$vuetify) 时,它就在那里。

一些控制台消息:

TypeError: Cannot read property 'breakpoint' of undefined
    at VueComponent.isMobile (VNavigationDrawer.ts?6ca0:193)
    at Watcher.get (vue.runtime.esm.js?f9ee:4473)
    ...

[Vue warn]: Error in getter for watcher "isMobile": "TypeError: Cannot read property 'breakpoint' of undefined"

found in

---> <VNavigationDrawer>
       <MySidebar> at my-library/src/components/MySidebar.vue
         <VApp>
           <App> at src/App.vue
             <Root>
...

TypeError: Cannot read property 'breakpoint' of undefined
    at VueComponent.isMobile (VNavigationDrawer.ts?6ca0:193)
    at Watcher.get (vue.runtime.esm.js?f9ee:4473)
    ...

[Vue warn]: Error in created hook: "TypeError: Cannot read property 'application' of undefined"

found in

---> <VNavigationDrawer>
       <MySidebar> at my-library/src/components/MySidebar.vue
         <VApp>
           <App> at src/App.vue
             <Root>

附加信息:

我遇到了完全相同的问题,并通过删除组件库文件夹中的 node_modules 文件夹解决了这个问题(即在您的情况下为 rm -rf my-library/node_modules)。

在 Vuetify 团队的帮助下,我发现问题是 Webpack 使用库中的 Vuetify 而不是应用程序中使用。这是由于在 my-app 上使用 npm link 来使用 my-library 以及作为开发依赖项安装在 my-library 上的 Vuetify。

一些可能的解决方案:

  • 在我的图书馆中,使用 npm install --only=prod 而不是 npm install。这将通过不在库上安装 Vuetify 来防止冲突。
  • 在我的应用程序中,将以下行添加到 vue.config.js
    const path = require('path');
    
    module.exports = {
        publicPath: process.env.VUE_APP_PUBLIC_PATH,
        configureWebpack: {
            resolve: {
                alias: {
                    /* Use vuetify from my-app, not from my-library */
                    vuetify: path.resolve(__dirname, 'node_modules/vuetify'),
                },
            },
        },
    };
    
    这将明确告诉 Webpack 从 my-app 选择 V​​uetify 安装。

其他不符合我要求的方案:

  • 停止使用npm link
  • 不要在 my-library 上安装 Vuetify,只在 my-app 上安装它