Dynamically loading an external webpack bundled ngModule as a route handler

前端 未结 1 1286
不思量自难忘°
不思量自难忘° 2021-02-07 07:42

We want to divide our large frontend projects into multiple separately deployed projects which are easier to work with. I am trying to include a bundled ngModule to handle a ro

1条回答
  •  滥情空心
    2021-02-07 08:06

    As you have mentioned

    The apps must be ignorant of each other's configuration.

    I had a similar problem in Angular2. I solved it by creating a sub-application. A separate sub-main.browser.ts and index.html file. It had its own dependencies, sharing the same node modules. Both main modules bootstrapping different app-component. We were working on Angular without angular-cli.

    In webpack config, I added

    entry: {
    
      'polyfills': './src/polyfills.browser.ts',
      'main' .   :     './src/main.browser.aot.ts',
      'sub-main' : '/src/sub-main.browser.ts'
    
    },
    

    and a more detailed HtmlWebpackPlugin. In the chunks, we load only modules that will be used in both the app. If we see polyfills is common.

       new HtmlWebpackPlugin({
        template: 'src/index.html',
        title: METADATA.title,
        chunksSortMode: 'dependency',
        metadata: METADATA,
        inject: 'head',
        chunks: ['polyfills','main']
      }),
    
      new HtmlWebpackPlugin({
        template: 'src/index2.html',
        title: 'Sub app',
        chunksSortMode: 'dependency',
        metadata: METADATA,
         inject: 'head',
        filename: './sub-app.html',
        chunks: ['polyfills','sub-main']
      }),
    

    The next task was to create separate endpoints for both sub apps for dev environment.

    devServer: {
          port: METADATA.port,
          host: METADATA.host,
          historyApiFallback: true,
          watchOptions: {
            aggregateTimeout: 300,
            poll: 1000
          },
          proxy: {
       "/sub-app": {
        target: "http://localhost:3009",
        bypass: function(req, res, proxyOptions) {
            return "/index2.html";
        }
      }
    }
        },
    

    Now when I build the project two different HTML files are generated. Each with their own javascript bundle dependencies and common assets. They can be deployed on a different server as well.

    I was able to finish my POC with lots of trial and error. My suggestion will be to look a step above angular. See how webpack is deploying your current project. And If you can configure it to serve your purpose.

    0 讨论(0)
提交回复
热议问题