Search code examples
typescriptvue.jswebpacksystemjs

Webpack shorten property name


We have Vue 2.x.x application (typescript) our application should be divided into modules. Like /users, /articles, /reports and etc. It is micro frontend architecture.

For example this solution: https://itnext.io/setup-a-micro-frontend-architecture-with-vue-and-single-spa-2c89528bf72f

We want to load these modules dynamically based on user permissions so we decided to choose SystemJS.

export const ApplicationModuleService = {
   
    
        createModule(name: string, url: string, activeWhen = "/", props = {}): RegisterApplicationConfig {
            return {
                name,
                app: () => window.System.import(url), //system js is loading from cdn. in global.d has definition
                activeWhen,
                customProps: props
            }
        }
    }

We have import of SystemJS from CDN and when we transpile this with webpack we are not able to use System.import, but we are forced to use window object.

When we try to use System.import webpack transpiles it into shortened property like: l.import(...) We have tried to create globally prop with webpack DefinePlugin, ProvidePlugin etc. but it didn't work.

Is there way, how to solve it? Thank you for your time


Solution

  • If you are using webpack already there is no reason to use System.js as module loader.

    Webpack has a built-in lazy loading modules capabilities.

    All you need to do is use the import('path/to/my/lazy/module'), which returns a Promise which will be resolved when the module is loaded. Webpack will handle the rest of the work.

    You code should look like:

    export const ApplicationModuleService = {
      createModule(name: string, url: string, activeWhen = '/', props = {}): RegisterApplicationConfig {
        return {
          name,
          app: () => import('path/to/lazy/module')
          activeWhen,
          customProps: props,
        };
      },
    };
    

    For a CDN support, you can specify the publicPath option.

    For more info read this