Building Your Single-SPA Micro Frontend App with Webpack & SystemJS

Here is an introduction to using micro frontend applications built with Single-SPA in various popular build tools.

Webpack 2+

Webpack 2+ supports import() for code splitting. Webpack 2+ is already widely used in other projects, so I won’t go into too much detail here.

import {registerApplication} from 'single-spa';

registerApplication('app-name', () => import('./my-app.js'), activeWhen);

function activeWhen() {
    return window.location.pathname.indexOf('/my-app') === 0;
}

SystemJS

In our previous projects, we used SystemJS because it facilitates secondary builds after application deployment. It’s also very convenient to use.

import {registerApplication} from 'single-spa';

// Import the registered application with a SystemJS.import call
registerApplication('app-name-1', () => SystemJS.import('./my-app.js'), activeWhen);

// Alternatively, use the more out-of-date System.import (instead of SystemJS.import)
registerApplication('app-name-2', () => System.import('./my-other-app.js'), activeWhen);

function activeWhen() {
    return window.location.pathname.indexOf('/my-app') === 0;
}

Webpack 1

Webpack 1 does not support Promise-based code splitting.

To achieve lazy loading, you must wrap require.ensure with a Promise.

import {registerApplication} from 'single-spa';

 //app1 without lazy loading and code splitting :(
import app1 from './app1';

// Register directly without lazy loading and code splitting :(
registerApplication('app-1', () => Promise.resolve(app1), activeWhen);


// app-2 uses dependency loading method
registerApplication('app-2', app2InPromise, activeWhen);

// Wrap it again
function app2InPromise() {
    return new Promise((resolve, reject) => {
        require.ensure(['./app-2.js'], require => {
            try {
                resolve(require('./app-2.js'));
            } catch(err) {
                reject(err);
            }
        });
    });
}

function activeWhen() {
    return window.location.pathname.indexOf('/my-app') === 0;
}

Article Link:

/en/archive/single-spa-webpack-systemjs/

# Related Articles