簡體   English   中英

在webpack中動態加載塊?

[英]Dynamically load chunks in webpack?

我們動態加載文件,即我們不知道哪些文件將在運行時加載。 同時,為了加快加載速度,我們希望將相關文件放在同一個塊中。

我怎么能用webpack做到這一點?

這就是我們所擁有的,它失敗了404錯誤(找不到1.1.bundle.js)

這就是webpack.config的樣子:

entry: {
   main: //...,
   related_files: [ //should create chunk for file1 and file2?
     './file1.js',
     './file2.js'
   ]
},

這是動態加載文件的代碼如下所示:

var dynamicFileName = //...

require.ensure([], function (require) {
  //should dynamically load the chunk containing dynamicFileName? 
  //fails with 'file1.js' or 'file2.js' 
  var modImpl = require(dynamicFileName);
  //...
});

更新1:錯誤消息是由未配置output.publicPath引起的。 但是,我從未創建過1.1.bundle.js 它似乎忽略了切入點。

更新2:即使在修復output.publicPath ,它也無法加載動態生成的文件名。 所以似乎webpack無法處理這個問題。

默認情況下,webpack嘗試將所有代碼捆綁在一個文件中。 如果您使用從file1.js / file2.js代碼main切入點,將的WebPack捆綁的所有文件的內容在main.js ,和第二個入口點related_files都只輸出文件1 /文件2的內容。

的WebPack通過處理這種情況CommonsChunkPlugin ,你的配置一定是這樣的:

entry: {
   main: //...,
   related_files: ['./file1.js','./file2.js']
},
plugins: [
   new webpack.optimize.CommonsChunkPlugin('related_files', 'related_files.js')
]

問題的第二部分是webpack解析require語句,並輸出1.1.bundle.js - 動態模塊,可以在代碼中加載require。 在您的情況下, dynamicFileName = 'related_files' ,而不是file1 / file2。

請參閱http://webpack.github.io/docs/code-splitting.html#split-app-and-vendor-code

暫無
暫無

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

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