2017-02-03 55 views
1

我們使用webpack 1.14.0來捆綁我們的應用程序。目前我們正在尋找一種方法,我們需要動態地按需加載一個包。WebPack按需動態加載包

我們的需求是從bundle中動態加載readme.md和example.md文件。 我使用require.ensure嘗試,下面是我想

//app.js entry point for webpack config 
require("./login"); //sample login file just contains console log stmnt. 

window.clickButton = function() { 
    require.ensure(['./ensureTest'], function (require) { 

     var a = require('./ensureTest'); 

    }); 

} 
console.log("App Loaded"); 

//ensureTest.js testing to load this module dynamically on demand 
define([], function(){ 
    console.log("Loaded ensure runtime"); 
}); 

樣本下面是我的WebPack配置

module.exports = { 
    entry: ["./app.js"], 
    output: { 
     filename: "bundle.js" 
    }, 
    module:{ 
     loaders:[ 
      { 
       test:/\.es6$/, 
       exclude : "node_modules", 
       loader:"babel-loader" 
      } 
     ] 
    }, 
    resolve:{ 
     extensions :['', '.es6','.js'] 
    } 
} 

當我運行的WebPack命令我能看到包。創建js和1.bundle.js文件。 問題是當我點擊一個按鈕,只有第一次點擊是看到「加載確保運行時間」消息顯示從1.bundle.js

再次點擊按鈕我看不到消息「已加載確保運行時「

我的動機是動態加載包及其包含的模塊。

回答

0

我很確定你只能加載一次。一旦你加載它,它已經在那裏,所以console.log不會再被調用。