A problem when I use webpack-5's libraryTarget:window

652 views Asked by At

I'm using the single-spa to create my apps. When I load the micro-frontend app, I did not use SystemJS, Just as follows:

export const runScript = async (url: string) => {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = url;
    script.onload = resolve;
    script.onerror = reject;

    const firstScript = document.getElementsByTagName('script')[0];
    (firstScript as any).parentNode.insertBefore(script, firstScript);
  });
};

const loadApp = async (appPath: string) => {
  try {
    await runScript(`/${appPath}/index.js`);
    console.log(appPath, '=', (window as any)[appPath]);
  } catch {
    console.log("load child app's javascript file error。");
  }
  return (window as any)[appPath];
};

singleSpa.registerApplication({
  name: 'app1',
  app: () => loadApp('app1'),
  activeWhen: '/app1,
  customProps: {
  },
});

So, I use libraryTarget:'window' in app1's webpack config.

devServer: {
  //...
  libraryTarget:'window'
},

It works fine when I use webpack4.

But when I update the webpack to webpack-5, it appears to have something wrong, the output code generated by webpack can not set the right value to the window object.

webpack-4: works fine at webpack-4

webpack-5: nothing in the object

Is this a problem of webpack-5?

1

There are 1 answers

2
Célian Garcia On

I personally use webpack5 for my single-spa-angular components. I have umd as libraryTarget

 "customWebpackConfig": {
     "path": "./extra-webpack.config.js",
     "libraryName": "mylib",
     "libraryTarget": "umd"
 }

https://github.com/milobella/application-web/blob/master/spa-menu/angular.json#L36-L37

And my app is well here under window when load the script https://github.com/milobella/application-web/blob/master/portal/src/main.ts#L9