Loading a webpack bundled ngModule dynamically to handle a route efficiently

In an effort to make working on our large frontend projects more manageable, we are looking to split them into multiple independently deployed projects. I am attempting to integrate a bundled ngModule to handle a route from within another app. It is crucial that the apps remain unaware of each other's configurations. The bundles will share some major dependencies, such as Angular, through global variables. While we may encounter some duplicate dependencies, we do not require tree shaking across the bundles.

The main issue arises when the root router displays the error:

Error: No NgModule metadata found for 'TestsetModule'.

This suggests that the child module is not being angular compiled on load or is failing to register its module for some reason. I assume manual compilation of the module might be necessary, but I am unsure how to utilize the https://angular.io/api/core/Compiler#compileModuleAndAllComponentsAsync method.

The root app loads the child module through a route:

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const load = require("little-loader");


const routes: Routes = [
  { path: ``, loadChildren: () => new Promise(function (resolve) {
      load('http://localhost:3100/testset-module-bundle.js',(err) => {
        console.log('global loaded bundle is: ', (<any>global).TestsetModule )
        resolve((<any>global).TestsetModule)
      }
    )
  })}
];

export const HostRouting: ModuleWithProviders = RouterModule.forRoot(routes);

I also attempted to use Angular router's string resolution syntax instead of the global approach, but encountered similar issues.

Here is the module being loaded, which is quite standard except for the global export:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpModule } from '@angular/http';
//import { MaterialModule } from '@angular/material';
import { FlexLayoutModule } from '@angular/flex-layout';
import { FormsModule }   from '@angular/forms';
import { LoggerModule, Level } from '@churro/ngx-log';

import { FeatureLoggerConfig } from './features/logger/services/feature-logger-config';


import { TestsetComponent } from './features/testset/testset.component';
import { TestsetRouting } from './testset.routing';

@NgModule({
    imports: [
        CommonModule,
        //MaterialModule,
        FlexLayoutModule,
        HttpModule,
        FormsModule,
        LoggerModule.forChild({
          moduleName: 'Testset',
          minLevel: Level.INFO
        }),
        TestsetRouting,
    ],
    declarations: [TestsetComponent],
    providers: [
      /* TODO: Providers go here */
    ]
})
class TestsetModule { }
(<any>global).TestsetModule = TestsetModule

export {TestsetModule as default, TestsetModule};

The webpack configuration for the root bundle is as follows. Note the global exports via the "ProvidePlugin".

const webpack = require('webpack');
const AotPlugin = require('@ngtools/webpack').AotPlugin;
const path = require('path');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const PolyfillsPlugin = require('webpack-polyfills-plugin');
const WebpackSystemRegister = require('webpack-system-register');


module.exports = (envOptions) => {
    envOptions = envOptions || {};
    const config = {

        entry: {
          'bundle': './root.ts'
        },
        output: {

          libraryTarget: 'umd',
          filename: '[name].js',//"bundle.[hash].js",
          chunkFilename: '[name]-chunk.js',
          path: __dirname
          },
          externals: {

          },
        resolve: {
            extensions: ['.ts', '.js', '.html'],
        },
        module: {
            rules: [
                { test: /\.html$/, loader: 'raw-loader' },
                { test: /\.css$/, loader: 'raw-loader' },

            ]
        },
        devtool: '#source-map',
        plugins: [
          new webpack.ProvidePlugin({
            'angular': '@angular/core',
            'ngrouter': '@angular/router',
            'ngxlog':'@churro/ngx-log'
          })

        ]
    };
    config.module.rules.push(
      { test: /\.ts$/, loaders: [
        'awesome-typescript-loader', 
        'angular-router-loader',
        'angular2-template-loader', 
        'source-map-loader'
      ] } 
    );
  }



    return config;
};

Similarly, the webpack configuration for the child bundle is provided below. Notice the "externals" section, which looks for Angular as a global.

module.exports = (envOptions) => {
    envOptions = envOptions || {};
    const config = {
        entry: {
          'testset-module-bundle': './src/index.ts'
        },
        output: {
          //library: 'TestsetModule',
          libraryTarget: 'umd',
          filename: '[name].js',//"bundle.[hash].js",
          chunkFilename: '[name]-chunk.js',
          path: path.resolve(__dirname, "dist")
          },
          externals: {
             'angular': '@angular/core',
             'ngrouter': '@angular/router',
             'ngxlog': '@churro/ngx-log'       
          },
        resolve: {
            extensions: ['.ts', '.js', '.html'],
        },
        module: {
            rules: [
                { test: /\.html$/, loader: 'raw-loader' },
                { test: /\.css$/, loader: 'raw-loader' },

            ]
        },
        devtool: '#source-map',
        plugins: [

        ]
    };

    config.module.rules.push(
      { test: /\.ts$/, loaders: [
        'awesome-typescript-loader', 
        'angular-router-loader',
        'angular2-template-loader', 
        'source-map-loader'
      ] }
    );
  }



    return config;
};

Lastly, here is my tsconfig file, which is read by 'awesome-typescript-loader'.

{
  "compilerOptions": {
    "target": "es5",
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "baseUrl": ".",
    "rootDir": "src",
    "outDir": "app",
    "paths": {
      "@capone/*": [
        "*"
      ],
      "@angular/*": [
        "node_modules/@angular/*"
      ],
      "rxjs/*": [
        "node_modules/rxjs/*"
      ]
    }
  },

  "exclude": ["node_modules", "src/node_modules", "compiled", "src/dev_wrapper_app"],
  "angularCompilerOptions": {
    "genDir": "./compiled",
    "skipMetadataEmit": true
  }
}

If you've made it this far, kudos! I was able to achieve the desired functionality when both bundles were part of the same webpack configuration and the child module was simply a chunk. This setup is supported by Angular. However, our requirement is to keep the children and parent isolated from each other until runtime.

Answer №1

As you previously stated

It is crucial that the apps remain unaware of each other's configurations.

I encountered a similar issue while working with Angular2. The solution I found was to create a sub-application with its own sub-main.browser.ts and index.html files. This sub-application had separate dependencies but shared the same node modules. Each main module was responsible for bootstrapping a different app-component. Keep in mind, we were developing in Angular without the use of angular-cli.

In my webpack configuration, I made the following additions:

entry: {

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

},

Additionally, I implemented a more detailed HtmlWebpackPlugin to load only the necessary modules for both apps. For example, the polyfills were common to both apps.

   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']
  }),

To complete the setup, I created separate endpoints for each sub-app in the development 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";
    }
  }
}
    },

After building the project, two distinct HTML files were generated, each with their own javascript bundles and shared assets. This setup allows for deployment on different servers if needed.

My experience involved a lot of trial and error to successfully complete this Proof of Concept. I recommend exploring beyond Angular and delving into how webpack handles deployment in your project. With some configuration adjustments, you may be able to achieve your desired outcome.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for duplicating a group containing loaded .obj models?

Initially, I created a new THREE.Object3D() and named it groupChair. I then loaded 3 obj files and added them to groupChair within the callback function. After that, I added the groupChair to the scene and it worked perfectly. However, I encountered an iss ...

Passport.js is throwing an error due to an unrecognized authentication

I need to implement two separate instances of Passport.js in my application - one for users and one for admins, both using JWT authentication. According to the official documentation, the way to differentiate between them is by giving them unique names. W ...

Converting HTML/Javascript codes for Android Application use in Eclipse: A Step-by-Step Guide

How can I implement this in Java? Here is the HTML: <head> <title>Google Maps JavaScript API v3 Example: Geocoding Simple</title> <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="styles ...

I am looking to utilize the JavaScript YouTube API to seamlessly upload a video from my website directly to YouTube

Currently facing an issue with uploading a video from my webpage to YouTube using the JavaScript YouTube API. The error code I'm receiving is "User authentication required" (401). Can anyone provide me with a demonstration example in JavaScript that s ...

What is a method for capturing the value of a nested input element without requiring its ID to be

Currently, I am facing a challenge in selecting the value of an input box from a user-generated ordered list of text boxes and logging its value to the console. It seems like I cannot find a way to select the value of a child's child element when the ...

Is there a way for TS-Node to utilize type definitions from the `vite-env.d.ts` file?

I am utilizing Mocha/Chai with TS-Node to conduct unit tests on a React/TypeScript application developed with Vite. While most tests are running smoothly, I am encountering difficulties with tests that require access to type definitions from vite-env.d.ts ...

Obtain the option tag's name

One of my challenges is working with a dynamically created dropdown in HTML and having a dictionary in the back-end to retrieve keys. As users keep adding options to the dropdown, I face the issue of not having a value attribute like this: <option valu ...

The 'changes' parameter is inherently defined with an 'any' type.ts(7006)

Encountering an error and seeking help for resolution. Any assistance would be highly appreciated. Thank you. Receiving this TypeError in my code. How can I fix this issue? Your guidance is much appreciated. https://i.sstatic.net/cWJf4.png ...

Upon calling set() on Map, the object returned does not conform to a Map data structure

I've been exploring the transition to using immutable.js for managing states: class Register extends Component<{}, Map<string, string>> { state = Map<string, string>(); onInputValueChange(e) { const { name, value } ...

CORS headers not functioning as expected for Access-Control-Allow-Origin

Can someone help me figure out how to add Access-Control-Allow-Origin: 'http://localhost:8080' in Node.js and Express.js? I keep getting this CORS error: Access to XMLHttpRequest at http://localhost:3000 from origin 'http://localhost:8080&ap ...

Making modifications to the state within a modal dialogue box

I am developing a note-taking application where users can write a title and note, and when they click submit, the note is displayed on the page. I want to implement an editing feature where clicking on the edit button opens a modal with the user's tit ...

Modifying the State in a Class Component

private readonly maxSizeOfDownloadedFiles: number = 1000000; state = { totalSum: this.maxSizeOfDownloadedFiles }; handleCallback = () => { this.setState({ totalSum: 12 }) alert('totalSum ' + this.state.totalSum); }; Upon executing the ...

Pagination of AJAX result on the client side using jQuery

My issue revolves around pagination in AJAX. I want to avoid overwhelming my search result page with a long list of returned HTML, so I need to split it into smaller sections. The Ajax code I am currently using is: $.ajax({ url: "getflightlist.php?pa ...

Implementing HTML page authentication with Identity ADFS URL through JavaScript

I have a basic HTML page that displays customer reports using a JavaScript function. The JavaScript makes an ajax call to retrieve the reports from a backend Spring REST API. In the Spring REST API, I have set up an endpoint "/api/saml" for authentication ...

Sending a POST request in Angular 7 with custom headers and request body

I have been attempting to make a post request with body and header. Despite trying various methods, I keep encountering an error on the server indicating that the parameter 'key' was not passed in. When testing the API in Postman, it works witho ...

Identifying the relationship between child and parent components in Vue.js

I am new to Vue.js and I am practicing some simple exercises on communication between Vue components. However, I am struggling with understanding who is a child component and who is a parent component. For example, consider the following code snippet: HTM ...

How can I match all routes in Express except for '/'?

I've been working on implementing an authentication system for my app that involves checking cookies. My approach was to use router.all('*') to handle every request, verify the cookie, and then proceed to the actual handler. However, I encou ...

What is the best way to ensure the initial item in an accordion group remains open by default when using NextJS?

I've successfully developed an accordion feature in NextJS from scratch and it's functioning flawlessly. However, I am looking to have the first item of the accordion open automatically when the page loads. Can anyone guide me on how to make this ...

Ways to include a link/href in HTML using a global constants file

I have a constants file with a links node that I need to integrate into my HTML or TypeScript file. Constants File export const GlobalConstants = { links: { classicAO: '../MicroUIs/' } } I created a public method called backToClassicAO ...

Modify the background color of a particular TD element when clicking a button using JavaScript and AJAX

When I click on the "Active account" button inside the designated td with the <tr id="tr_color" >, I want the value "1" to be added to the 'active_account' column in the database. I have been successful with this functionality. However, I a ...