簡體   English   中英

Webpack依賴關系管理和Vue.js異步組件加載

[英]Webpack Dependency Management and Vue.js async component loading

我正在嘗試實現Vue.js動態async component注冊。 這個視頻給了我完全正常的代碼,但它加載了所有模塊,即使它們沒有被使用。

import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'
// Require in a base component context
const requireComponent = require.context(
  '../components/base', false, /base-[\w-]+\.vue$/,
)
requireComponent.keys().forEach(fileName => {
  // Get component config
  const componentConfig = requireComponent(fileName)
  // Get PascalCase name of component
  const componentName = upperFirst(
    camelCase(fileName.replace(/^\.\//,
      '').replace(/\.\w+$/,
      '')),
  )
  // Register component globally
  Vue.component(componentName, componentConfig.default || componentConfig)
})

我試圖實現的是創建異步組件。 像這樣

import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'
// Require in a base component context
const requireComponent = require.context(
  '../components/base', false, /base-[\w-]+\.vue$/,
)
requireComponent.keys().forEach(fileName => {
  const componentPath = fileName.replace('./', '../components/base/');
  // Get PascalCase name of component
  const componentName = upperFirst(
    camelCase(fileName.replace(/^\.\//,
      '').replace(/\.\w+$/,
      '')),
  )
  // Register component globally
  Vue.component(componentName, () => import(componentPath))
})

如果vue以上代碼的情況引發錯誤

vue.esm.js:591 [Vue warn]: Failed to resolve async component: function () {
    return __webpack_require__("./lib lazy recursive")(componentPath);
  }
Reason: Error: Cannot find module '../components/base/base-button.vue'

如果我手動寫下Vue.component('BaseButton', () => import('../components/base/base-button.vue'))它的工作沒有問題但是當我嘗試動態地執行它時它會失敗。 是否可以進行這樣的async component注冊,如果是這樣的話?

這也不起作用:

const button = '../components/base/base-button.vue'
Vue.component('BaseButton', () => import(button))

只有我確實將字符串改為導入函數。

模塊路徑完全動態時,無法使用import 查看文檔

完全動態的語句(例如import(foo)將失敗,因為webpack至少需要一些文件位置信息。 這是因為foo可能是系統或項目中任何文件的任何路徑。 import()必須至少包含有關模塊所在位置的一些信息,因此捆綁可以限制在特定目錄或文件集中。

您沒有為require.context指定mode參數,默認為“sync”; 這意味着所有匹配的模塊將立即加載。 您想使用“lazy”為每個模塊生成一個可加載惰性的塊。

未經測試,但我想它會是這樣的:

const context = require.context('../components/base', false, /base-[\w-]+\.vue$/, 'lazy');

context.keys().forEach(fileName => {
  const componentPath = fileName.replace('./', '../components/base/');

  // Get PascalCase name of component
  const componentName = upperFirst(
    camelCase(fileName.replace(/^\.\//,
      '').replace(/\.\w+$/,
      '')),
  );

  // Register component globally
  Vue.component(componentName, () => context(fileName));
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM