Importing a JavaScript file into an Angular 2 application

Currently, I'm in the process of developing an angular2 application using TypeScript.

The Situation:

Within my project, there exists a module named plugin-map.ts which is structured as follows:

import { Type } from '@angular/core';

import { SomeComponent } from './plugins/some.component';

export const PluginMap: { [key: string]: Type<any> } = {
    'e690bec6-f8d1-46a5-abc4-ed784e4f0058': SomeComponent
};

This code is transpiled into a file named plugin-map.js, taking the form shown below:

"use strict";
var some_component_1 = require('./plugins/some.component');
exports.PluginMap = {
    'e690bec6-f8d1-46a5-abc4-ed784e4f0058': some_component_1.SomeComponent
};
//# sourceMappingURL=plugin-map.js.map

In various modules, I import the PluginMap like this:

import { PluginMap } from './plugin-map';

My Goal:

Now, my aim is to dynamically generate the plugin-map.js when the server starts running. Essentially, I want to eliminate the need for plugin-map.ts and solely rely on the generated plugin-map.js. Moreover, I want to remove any compile-time dependencies associated with that file.

My Attempt:

To achieve this, I replaced the import statements with declarations like this in modules where I reference the PluginMap:

declare const PluginMap: { [key: string]: Type<any> }; 

Naturally, at runtime, I encountered an error stating

Error: (SystemJS) 'PluginMap' is undefined
. As a next step, I tried loading plugin-map.js explicitly from my index.html, as illustrated below:

...
<script src="js/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
      System.import('./app/plugins/plugin-map.js').catch(function (err) { console.error(err); });
      System.import('app').catch(function(err){ console.error(err); });
</script>
...

Although the browser does request the plugin-map.js file upon launching the application, the

Error: (SystemJS) 'PluginMap' is undefined
issue persists.

The Question:

How and where should I load the dynamically generated plugin-map.js to ensure everything functions properly?

Answer №1

In order to ensure that PluginMap is accessible in the global context, it was necessary for the generated plugin-map.js file to be structured like this:

var some_component_1 = require('./plugins/some.component');
PluginMap = {
    'e690bec6-f8d1-46a5-abc4-ed784e4f0058': some_component_1.SomeComponent
};

Instead of the alternative structure shown below:

"use strict";
var some_component_1 = require('./plugins/some.component');
exports.PluginMap = {
    'e690bec6-f8d1-46a5-abc4-ed784e4f0058': some_component_1.SomeComponent
};
//# sourceMappingURL=plugin-map.js.map

After making these changes, everything appears to be functioning properly.

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

The styles of a jQuery Mobile listview aren't updating properly when the list items are emptied and then dynamically re-created

When I have a listview that dynamically creates its list items using JavaScript code, everything works perfectly the first time the code runs. However, upon subsequent executions, the list is generated correctly but loses the jQuery Mobile styling. Despite ...

The Safari browser showcases the dropdown area in a unique way

Is there a way to make the dropdown area size consistent across different browsers like Chrome, Firefox, and Internet Explorer? Here is the code snippet: <div id="category-dropdown" style="float:left; display:inline-block; padding:8px 0px 0px 5px; dis ...

Which specific element should the userEvent.type(...) function target in order to work effectively with MUI's DesktopDatePicker TextField component?

Is there a way for me to input text into the TextField input within the MUI datepicker using react-testing-library's user-event? I've noticed that there is a mask applied to the input. I attempted to use userEvent.type(inputEl, '1') an ...

The module '@material-ui/lab' could not be located

I'm currently developing a front-end page that requires the use of @material-ui/lab. I encountered an issue after installing the package using npm, where I received a typescript error during compilation: TS2307: Cannot find module '@material-ui/l ...

What is the best way to send an array of strings through an AJAX call?

Utilizing ajax to send an array of strings to another page has been a bit tricky for me. Here is the array located on nomes.php [ 'Home','A empresa','funcionarios','Quem Somos?','Historia','Inicio&ap ...

Examples of using React tables with Material-UI, such as the Material-UI kitchen sink demo, will showcase how to

Can someone help me figure out why the values are not visible in the react table MUI kitchen sink? When I switch to JSON, the header is visible but the data in the table disappears. Both 'data' and 'data1' have the same structure accord ...

Adjusting the height of a Vue component to 100% triggers a change in height whenever a re-render occurs

In my Vue component, there is a class called "tab-body-wrapper" that serves the purpose of displaying the "slot" for the active tab. However, I encountered an issue while troubleshooting where the height of the ".tab-body-wrapper" component reduces during ...

I am currently working on coding a function that will search an array to determine if a specific item is present. If the item is found, a variable will be set to true;

So, I have this array of prices for various items like bread, apple, noodles, beef, milk, and coke. const prices = [ ["bread", 20], ["apple", 50], ["noodles", 100], ["beef", 40], ["milk", 32], ["coke", 25], ]; And here's the JavaScript co ...

javascript to retrieve data by reducing

Here is the code snippet I am working with: var points = 4; var yModifier = []; for (var i = 0; i <= points; i++) { yModifier.push([]); }; yModifier.forEach( (a, j) => { var start = j; var end = start + points; fo ...

Jquery events continue to accumulate without initiating until the preceding event has completed

Looking at the code below, it essentially fades all the images to 70% within the contact class. When an image is hovered over, its opacity changes to 100%. If multiple images are hovered over or multiple hover events occur in succession, the events will st ...

transferring information seamlessly in Ionic using Angular router without the need for navigation

I have a list of names that are displayed, and when I click on any name in the list, it should take me to another page without actually navigating to that path. names.page.html: <ion-content> <ion-list *ngFor='let person of people'&g ...

Utilizing Jquery to Load JSON Arrays as Tooltip Messages

I have successfully loaded the descriptions of my JSON variable into my script as tooltips. However, I am encountering two issues: When hovering over one sentence in my table, tooltips for all four sentences appear. It seems like I am unable to revert my ...

Creating a shimmering glow for a dynamic AJAX div block in real-time

I created an Ajax code that retrieves results from a txt file in real time, which are then automatically displayed in a div block using the following lines: if (xmlhttp.responseText != "") { InnerHTMLText = xmlhttp.responseText + document.getElementBy ...

What steps should I follow to upgrade my Angular 11 to the newest version while ensuring that all packages and tools are

Upon completing the update and attempting to run the project using ng serve, an error occurred. An uncaught exception was encountered: Module '@angular/compiler-cli/src/tooling' could not be found ...

Tips for sharing JSON data between JavaScript files

Here is the initial script setup to utilize static .json files for displaying and animating specific content. The code provided is as follows: var self = this; $.getJSON('data/post_'+ index +'.json', function(d){ self.postCa ...

How do I trigger a click on a menu item that is lazy loaded when testing Angular with Cypress?

I attempted to execute a small cypress test by trying to navigate to a lazy loaded page, but unfortunately it did not work as expected. The URL path I aimed for was: 'angular-page/angular-page-content1' My approach: describe('1st. test&apos ...

Executing a function in cesium.js upon the occurrence of an event

I've set up a div like this: <div id="cesiumContainer" class="fullSize"></div> <div id="loadingOverlay"><h1>Loading...</h1></div> <div id="toolbar"><input type="search" id="search" placeholder="Search by l ...

Tips for making an input form that triggers an alert popup

After creating an HTML form with text input, utilizing Javascript for validation as shown below: I am trying to trigger an alert box thanking the user for entering data when the submit button is clicked. I have faced challenges in implementing this witho ...

What are the various functions that an Alert button can serve in Ionic?

What are the potential choices for the role designation of a button within an Alert using the Ionic framework (v5)? The official documentation only lists cancel: https://ionicframework.com/docs/api/alert#buttons If desired, a button can have a role prop ...

The property in the object cannot be assigned because it is read-only: [object Object]

I am currently developing an Ionic application using the Angular framework and NGRX. I have encountered an issue with a selected checkbox. The problem arises when: First, I fetch a list of vehicles from a database using a service. Then, I set the propert ...