简体   繁体   English

WebPack按需动态加载bundle

[英]WebPack Dynamically load bundle on demand

We are using webpack 1.14.0 to bundle our application. 我们使用webpack 1.14.0捆绑我们的应用程序。 Currently we are looking for an approach where we need to load a bundle on demand dynamically. 目前,我们正在寻找一种方法,我们需要动态地按需加载捆绑包。

Our requirement is to load readme.md and example.md files dynamically from bundle. 我们的要求是从bundle动态加载readme.md和example.md文件。 I am trying using require.ensure , below is the sample that I am trying 我正在尝试使用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");
});

Below is my webpack config 下面是我的webpack配置

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

When I run WebPack command I am able to see bundle.js and 1.bundle.js file created. 当我运行WebPack命令时,我能够看到创建了bundle.js和1.bundle.js文件。 Problem is when I am clicking on a button, only for the first time click is see "Loaded ensure runtime" message which is showing from 1.bundle.js 问题是当我点击一个按钮时,只有第一次点击是看到“已加载确保运行时”消息,该消息显示自1.bundle.js

Clicking again on the button I cannot see the message "Loaded ensure runtime" 再次单击按钮我看不到消息“已加载确保运行时”

My overall motive is to load the bundle and its contained module dynamically. 我的总体动机是动态加载bundle及其包含的模块。

I'm pretty sure you can only load it once. 我很确定你只能加载一次。 Once you load it, it's already there so the console.log won't get called again. 一旦你加载它,它已经存在,所以console.log不会再被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM