Create individual SPA bundles with Webpack

webpack creates a split point per async require statement (require.ensure or AMD require([])). So you need to write a require([]) per lazy-loaded part of your app.

Your SPA only has a single entry point: the (client-side) router. Let’s call it app.js. The pages are loaded on demand and ain’t entry points.

webpack.config.js:

module.exports = {
    entry: {
        app: './app'
    },
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: '[name]-bundle.js'
    }
}

app.js:

var mod = window.location.hash.split("https://stackoverflow.com/")[0].toLowerCase();
alert(mod);

switch(mod) {
    case "contacts":
        require(["./pages/contacts"], function(page) {
            // do something with "page"
        });
        break;
    case "tasks":
        require(["./pages/tasks"], function(page) {
            // do something with "page"
        });
        break;
}

Alternative: Using a “context”.

When using a dynamic dependency i. e require("./pages/" + mod) you can’t write a split point per file. For this case there is a loader that wrapps a file in a require.ensure block:

app.js

var mod = window.location.hash.split("https://stackoverflow.com/")[0].toLowerCase();
alert(mod);

require("bundle!./pages/" + mod)(function(page) {
    // do something with "page"
});

This is webpack-specific. Don’t forget to npm install bundle-loader --save. Check the correct casing, it’s case-sensitive.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)