2

问题:在我的vue-cli 4应用程序中,我想要build:生成生产包的脚本,.vue-components在某些情况下不包含特定的脚本。在其他情况下,它们应该被包括在内。此外,这些组件存储在应用程序本身 - 而不是外部库中。

我试过:动态导入.vue-components- 假设我有一个数组:

const customPreset = ['WidgetFirst', 'WidgetSecond', ...]

和空对象:

const widgets = {}

所以我试着做这样的事情:

customPreset.forEach(v => { Object.assign(widgets, { [v]: () => import('./' + v + '.vue') }) })
export default widgets

更改customPreset为其他数组将允许导入另一组组件...

但这不起作用,因为import()不能用表达式操作。

那么,.vue-components在各种情况下如何将各种内容包含到生产包中呢?也许它可以通过调整来实现vue.config.js

4

1 回答 1

0

您正在寻找的是lazy loaded components. 在 Vue 中,它们可以在多个点上使用。

  1. vue-router - 您可以为每个路由导入组件,仅在需要时加载:

这是如何定义一个将由 webpack 自动进行代码拆分的异步组件:

const Foo = () => import('./Foo.vue')

您还可以将组件分组到同一个块中

const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue')
const Bar = () => import(/* webpackChunkName: "group-foo" */ './Bar.vue')
const Baz = () => import(/* webpackChunkName: "group-foo" */ './Baz.vue')
  1. 第二个选项是Dynamic/Async components,可以在 .vue 文件中使用,如下所示:
Vue.component(
  'async-webpack-example',
  // The `import` function returns a Promise.
  () => import('./my-async-component')
)

它甚至支持直接从包装盒中加载状态:

const AsyncComponent = () => ({
  // The component to load (should be a Promise)
  component: import('./MyComponent.vue'),
  // A component to use while the async component is loading
  loading: LoadingComponent,
  // A component to use if the load fails
  error: ErrorComponent,
  // Delay before showing the loading component. Default: 200ms.
  delay: 200,
  // The error component will be displayed if a timeout is
  // provided and exceeded. Default: Infinity.
  timeout: 3000
})
于 2020-04-02T06:59:06.017 回答