vue库打包后依赖注入失效、[Vue warn]: $xxx is readonly问题

284 阅读1分钟

在开发vue组件库时使用了vue-template-compiler、vue-class-decorator、vue-property-decorator等依赖时出现以下问题:

  • 用户开发环境运行时的组件库中的依赖注入(@Provide,@Inject)变量无法获取到,一直是undefined

  • 控制台出现大量警告如[Vue warn]: $attrs is readonly,[Vue warn]: $listeners is readonly;

查询资料得知,vue-template-compiler与vue版本不一致时会出现上述警告,但是我这里版本都是一样的,库开发环境运行是没问题的,只有在用户开发环境才有问题,最终想到在库代码打包配置中应当将使用的vue-property-decorator 、vue-class-decorator、vue-template-compiler等依赖从打包代码中排除,在运行时(runtime)再去从外部获取这些扩展依赖(external dependencies) ,果然解决。

解决问题后vue.config.js部分配置如下:

module.exports={
    configureWebpack:{
    // 防止将某些 import的包(package)打包到bundle中,而是在运行时(runtime)再去从外部获取这些扩展依赖(external dependencies) 。
        externals:[
            // 正则匹配所有vue开头的依赖,如 vue、vue-class-decorator、vue-property-decorator、vue-template-compiler等
            /^(vue)/i
        ]
    }
}

同时将排除后的依赖添加到package.json的dependencies中,这样用户在安装我们的库时会自动安装所需依赖。