为什么webpack代码拆分不能按预期工作?

时间:2016-08-21 05:29:51

标签: javascript webpack

我希望jquery全球可用,.js/uploader.js仅在/login按需评估。这是我尝试的:

index.js

require("./css/main.scss")
$ = require("jquery")
require.ensure(["./js/uploader"], function(require) {
    if (window.location.pathname=='/login') {
        var uploader = require("./js/uploader")
    }
});

webpack.config.js:

module.exports = {
    entry: "./index.js",
    output: {
        path: '../wdksw/static/js',
        publicPath: 'static/js/', 
        filename: "bundle.js", 
    }, 
    module: {
        loaders: [
            { test: /\.css$/, loader: "style!css" }, 
            { test: /\.scss$/, loaders: ["style", "css", "sass"]}, 
        ], 

    }
};

HTML:

<script type="text/javascript" src="/static/js/bundle.js"></script> 

但是当我在浏览器中发出不是/login的请求时,1.bundle.js也会被请求,这不是我想要的。所以我该怎么做?我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

您的require.ensure应该在if声明中:

if (window.location.pathname == '/login') {
    require.ensure(["./js/uploader"], function(require) {
        var uploader = require("./js/uploader")
    });
}

现在,您的捆绑包只会在if声明中的匹配条件下添加到您的头部。