【问题标题】:How can I use standalone vue library in a vue application?如何在 vue 应用程序中使用独立的 vue 库?
【发布时间】:2021-01-05 08:14:14
【问题描述】:

我正在尝试在 vue 应用程序中使用由脚本标签加载的 vue 组件库。该组件库使用 webpack 设置并使用设置 externals 排除所有 vue 依赖项。因此,使用该库的主机包必须提供 vue 和其他所需的依赖项。 组件库本身正在使用带有脚本vue-cli-service build --target lib 的vue cli 来构建lib.umd.js 文件。在我的主机包的index.html 中,我只是通过脚本标记包含该文件。主机包的 webpack 设置使用config.externals(['@test/my-component-library']) 排除正在外部加载的组件库。在主机包中,我正在使用这样的组件库:

import { MyComponent } from '@test/my-component-library'

当我运行我的应用程序时,我收到以下错误:Uncaught SyntaxError: Invalid or unexpected token。此错误发生在我的主机包的以下行中:

/*!*******************************************************!*\
  !*** external "@test/my-component-library" ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("module.exports = @test/my-component-library;//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiQHRlc3QvbXktY29tcG9uZW50LWxpYnJhcnkuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vZXh0ZXJuYWwgXCJAdGVzdC9teS1jb21wb25lbnQtbGlicmFyeVwiPzFjOTAiXSwic291cmNlc0NvbnRlbnQiOlsibW9kdWxlLmV4cG9ydHMgPSBAdGVzdC9teS1jb21wb25lbnQtbGlicmFyeTsiXSwibWFwcGluZ3MiOiJBQUFBIiwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///@test/my-component-library\n");
/***/ })

有谁知道为什么 webpack 会生成这样的代码以及我该如何纠正它?

【问题讨论】:

  • 来自webpack.js.org/configuration/externals 不知道要设置导出模块的类型如root?
  • 如果我使用config.externals({'@sldo/sldo-crm-kundenaktionen-plugin': {root: '@sldo/sldo-crm-kundenaktionen-plugin' } }),错误就消失了。但现在我收到Cannot read property 'MyComponent' of undefined。这是因为我的导入 import { MyComponent } from '@test/my-component-library' 不起作用。我该怎么办?

标签: javascript vue.js webpack


【解决方案1】:

我想我找到了解决方案。所以首先我对externals 的配置有误。正确的配置是:

config.externals({
  '@test/my-component-library': {
    root: '@test/my-component-library',
    commonjs2: '@test/my-component-library',
    commonjs: '@test/my-component-library',
    amd: '@test/my-component-library',
  },
})

在组件库中,我必须添加 webpack 配置 config.output.library('MyComponentLibrary') 以便对象 MyComponentLibrary 在窗口范围内全局可用。然后我不得不删除主机包中的导入语句。要注册组件,我必须将此行添加到我的 vue 文件中:

components: {
  'MyComponent': MyComponentLibrary.MyComponent,
}

但现在我遇到了另一个问题。组件库本身正在使用 vuetify(这是另一个组件库)。但我也将 vuetify 添加到 externals 选项,因为我的主机包已经包含 vuetify。现在我收到了很多Unknown custom element 异常。所以显然我的组件库在我的主机包中找不到 vuetify 组件。这个问题有解决办法吗?

【讨论】:

  • 我认为如果您发布一个新问题,您将获得更好的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-08
  • 2021-06-08
  • 2020-09-06
  • 2017-12-16
  • 2020-10-17
  • 1970-01-01
相关资源
最近更新 更多