The presence of an Angular Element within an Angular application can lead to a problematic cycle of constant reloading,

, I am encountering issues with integrating Angular Elements as plugins into my Angular application. The problem arises when building the element with "--prod" - it functions properly with "ng serve" in my development setup but causes infinite reloading when using "ng serve --prod" or after running "ng build --prod" for production. An attempt to mitigate this involved building the element with "--optimization=false", which worked for the production app but not in the development setup. I had hoped that building an Angular Element with "--prod" would work seamlessly for both scenarios. Is there a feasible solution to resolve this discrepancy? Further details reveal our objective at work of implementing configurable plugins within our Angular site where the server dictates the active plugins. While exploring dynamic loading of Angular modules, we encountered challenges that were set aside for future consideration. Subsequently, we explored Angular Elements for its potential, only to face obstacles in adhering to the recommended build process. Initial steps included setting up a core application as the plugin host and creating an Angular Element for the plugin itself. Modifications were made to various configuration files and code snippets according to online tutorials and recommendations. The overall structure entailed scripts in the package.json file to facilitate building processes, along with adjustments to component templates and TypeScript files to accommodate the desired functionality. Despite the workaround implemented to ensure functionality in both development and production environments by loading different builds based on optimization settings, it leaves room for improvement regarding optimized code usage. For further insights and hands-on experience with the issue, you can refer to the GitHub repository link provided above. Your feedback and suggestions are welcome as we strive to enhance this integration for a seamless user experience.

Answer №1

Success! I've cracked the code!

The culprit, as it turns out, is running multiple webpack projects simultaneously in the same environment. Essentially, when you compile projects with webpack, they undergo some runtime bootstrapping that relies on a specific global function (webpackJsonp). When more than one webpack setup tries to perform this bootstrapping in the identical context, it triggers the issues outlined here. (For a more detailed breakdown, check out this explanation - https://example.com/unique-link-here)

A GitHub comment offers a workaround without diving into the step-by-step process - https://example.com/different-link-here. Below, I'll share my tailored fix.

We can tweak the webpack configuration to rename the webpackJsonp for our web component, ensuring harmony between different Angular projects (or any webpack-built applications).

The Fix

To start, we need to add the @angular-builders/custom-webpack package to modify the default webpack setup in Angular CLI.

npm install --save-dev @angular-builders/custom-webpack

Next, we need to update our angular.json file to utilize the new builder and introduce a fresh property value, customWebpackConfig, under options. This feature specifies a path to a new file we're about to create and sets a merge strategy to append configurations to the output section of webpack settings.

angular.json
...
      "architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./extra-webpack.config.js",
              "mergeStrategies": { "output": "append"}
            },
...

Lastly, we simply create an extra-webpack.config.js file in the directory containing angular.json. The file should include the following snippet:

module.exports = {
    output: {
        jsonpFunction: '<webcomponent-prefix>-webpackJsonp'
    }
}

If you alter the value of jsonpFunction from its default

webpackJsonp</code, the setup will still function appropriately. Personally, I chose to preserve the function name but incorporate a prefix for my web component application. Ideally, you could have multiple webpack setups coexisting in the same environment, provided each possesses a unique <code>jsonpFunction
.

Recompile your web component, and voilà, problem solved!

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

Vue-bootstrap spinbutton form with customizable parameters

I am in need of a custom formatter function for the b-form-spinbutton component that depends on my data. I want to pass an extra argument to the :formatter-fn property in the code snippet below, but it is not working as expected. <b-form-spinbutton :for ...

What could be causing the issue with the custom Button component not functioning correctly on hover when using MUI Button alongside Tooltip

After creating a Custom Button that envelops a MUI Button to handle default props and other aspects, I encountered an issue that persisted despite simplifying the example. Below is the code snippet along with a link to a codesandbox for reference: CodeSand ...

JQuery failing to trigger AJAX function

I'm struggling with what seems like a simple issue and it's driving me crazy. The problem lies in this straightforward section of the website. I have a .js file that uses ajax to save a post into the database when the submit button is clicked. A ...

What is the process for displaying all cookies in node.js?

I recently wrote some node.js code to retrieve cookies for a specific route. router.get('/', function (req, res, next) { var cookies = req.cookies; res.render('cartoons', { Cookies: cookies, }); }); In my cartoons Jade file, the ...

Running `ng start angularProject` or `npm install` will generate additional files in the project's

I'm encountering a major issue where every time I create a new project using 'ng start' or run 'npm install', extra files are being generated in the root folder like this. https://i.stack.imgur.com/BUphZ.png Here is my package.js ...

You are unable to access the array beyond the scope of the function

I am encountering an issue with a function I wrote: function gotData(data){ result = data.val() const urls = Object.keys(result) .filter(key => result[key].last_res > 5) .map(key => ({url: 's/price/ ...

When an input event is dispatched in a unit test, the value changes of a form are not activated

Currently, I am testing a scenario where I need to verify if a value changes on the form when input is typed in. This particular project utilizes Nrwl nx as well as jest for testing purposes. The component code snippet is as follows: export class InputNu ...

Ways to execute a function when a button is clicked with a shared variable?

When creating buttons in HTML to control video speed, I encountered a strange issue. After successfully implementing the buttons for one video, they only worked on a second video and had no impact on the first one. Deleting the second video seemed to resol ...

how to implement a delay in closing a window using JavaScript

I am currently developing a Google Chrome extension and I want to express my gratitude to everyone here for tolerating my sometimes silly questions. The functionality of the extension is quite basic but it works smoothly. However, I am facing an issue wher ...

Guide on integrating buefy (a vue.js component library) into your Laravel blade template

I'm currently integrating buefy into my project, but I'm encountering issues with using vue.js on Laravel 5.8. Can anyone offer assistance? Here is the code snippet from my app.js: require('./bootstrap'); window.Vue = require('v ...

Utilizing Angular 2 and Node JS for both backend and frontend development

I'm a bit puzzled on how to go about implementing this, particularly with routing. How should I handle routing for both the backend and frontend, considering that the source (CSS, HTML, JS) might differ between the two? Thank you. ...

Identify the difference between a regular function and a constructor in JavaScript

How can we determine whether a function in javascript is a simple, plain (anonymous) function, or a constructor (a function with a prototype)? I have developed the following function for this purpose: function checkFunctionType(value) { var ownPropert ...

Utilize Pipe for every instance of a variable in the Controller

In my controller, I have multiple requests (POST, GET etc.) where the path includes an id parameter that needs to be a number string. I want to validate this parameter once and have it apply to all instances. Here is the current code snippet: @Get(&apo ...

How do I inform Jest that spaces should be recognized as spaces?

Here is some code snippet for you to ponder: import { getLocale } from './locale'; export const euro = (priceData: number): string => { const priceFormatter = new Intl.NumberFormat(getLocale(), { style: 'currency', currenc ...

Troubleshooting Issue: Angular 6 - Authentication token interceptor not including headers

After experimenting with various approaches using Angular 6 for the past couple of days, I recently tried implementing a solution mentioned in this post: . Despite my efforts, the header in the requests still remains unset. import {Inject, Injectable} fro ...

troubles with compatibility between bootstrap.css and IE11

I am currently developing a web application using AngularJS and bootstrap.css. While everything appears fine on Chrome, I am facing some formatting issues on both Firefox and IE11. HEAD <head> <meta charset="utf-8"> <meta http-equi ...

Is there a way to create a function that can show the pathway on the Browser Console?

I am looking to create a function that will show the path in the Browser Console when a link in the menu of a sub-category is clicked. The menu setup resembles this () on an e-commerce website. For instance: Perfume => ForMen => Cologne How can I r ...

Attaching a $UI element to a <div> tag with JQuery may result in unexpected errors and issues

Attempting to connect SagePayments card elements to the paymentDiv. Followed their sample project for guidance, but encountering issues with populating the elements when running the program with a custom Sandbox merchantID and merchantKey. Chrome's de ...

Transform a C# DateTime object into a JavaScript date format

In my Javascript function, I am handling a C# DateTime received from MVC. If the date is null, it should return "-", and if it's a valid date, it should be returned in the formatted date. IMPORTANT: The date must be sent in the specified format from ...

Ways to retrieve data from ngrx and display it in a component file

I have recently incorporated the ngrx library into my project to create a more dynamic model for handling data. After setting up my actions, reducers, and effects files, everything seems to be working as intended because I can observe the populated model w ...