Exporting an angular component as a module

I have successfully created a widget using Angular elements that works well in HTML. However, I am unsure of how to export it as a module for use in other Angular, React, Vue web applications. I want to be able to import

import { acmaModule } from package-name
instead of
const acmaModule = require('widge.js')
.

In my Angular code:

export class AppModule {
  initWidget(options: any){
    console.log('options received', options)
  }

  constructor(private injector: Injector) {
    // Expose Window function
    (<any>window).acmeWidget = { initWidget: this.initWidget  };

     // Survey Widget
    const surveyComp: any = createCustomElement(SurveyComponent, { injector: this.injector });
    customElements.define('acme-survey', surveyComp);
  }

  ngDoBootstrap() {}
}

And in the HTML file:

<html>
....
<script src="../survey-widget.js">
<script>
 acmeWidget.initWidget({
  test: "Hello world"
 })
</script>
....
</html>

Answer №1

To simplify the process of packaging modules for external references, you can create an export file and specify the modules you want to include in it.

For instance, you can create a file named export.ts within the src directory. Then, populate the file with something similar to the following code snippet, assuming that your main AppModule is located at src\AppModule.ts:

//content of export.ts
export * from './AppModule';
...

In your ng-package.json configuration file, make sure to designate export.ts as the entry file. This can be achieved by including the following section:

//content of ng-package.json
{
  "$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
  "dest": "../../dist/<your built package name>",
  "lib": {
    "entryFile": "src/export.ts"
  }
}

Once you have built your project, you can publish the artifact using the command npm publish. This will allow others to install and import your packaged modules via npm. If your project is named test-project, the process would look something like this:

ng build test-project --prod

# after build is done:
cd dist/test-project
npm publish

For more information on npm publish, refer to the documentation provided.

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

Enhancing Data Tables with Jquery: Implementing Column Filtering for Multiple Elements within Table Cells

I am looking to utilize jQuery datatables for filtering a column that may contain multiple values within a single td. To achieve this, I referenced the example provided in the datatables documentation. In the image below, my goal is to filter the office ...

What steps can be taken to ensure that the onchange event functions properly with radio input

I am facing an issue with my input field as the value changes automatically when an option is selected. However, I want this functionality to also work the same way when a radio input option is selected. How can I modify the code to achieve this? func ...

Modify the state's value by updating it when your information is stored in an array

I am currently working with contact numbers stored in an array and utilizing native-base for data viewing. this.state = { leadProfile: { contactNumber: [ { "lead_contact_number": "0912 312 412312", "lead_contact_nu ...

Encountering a Node.js issue when attempting to properly sanitize data before inserting it into MySQL

This is a snippet of code that I am using to insert data into a MySQL table. Before running the query, I escape the values like so: const mysql = require('mysql'); const R = require('ramda'); class Repository { constructor(connectio ...

How to display an object in JS format using React?

Currently, I am tackling a project that presents me with the following situation: myjson: { completeName: "my name is {this.state.myName+ " "+this.state.surname}" } component.js var Component = React.createClass({ getInitialState: function() { ...

What is the best way to show a filtered list using a state that was created with useState in React?

Check out my code in CodeSandbox, consisting of 4 divs categorized as "Book" and "Article". There are buttons at the top to toggle between displaying all divs, only books, or only articles. However, clicking on any button currently shows all divs and gives ...

Using an array as an argument for .map() results in an error

This is quite unusual. Currently, I am passing an array containing a single object to the Render method of a React component: let content = this.state.links.map(link => { // eslint-disable-line return ( <li key={link._id}> <a href ...

Passing the results of sequelize through express after the completion of a forEach iteration

In an express route, I am running a somewhat complex sequelize query that requires me to run a second query afterward to append necessary data to the result: //Get inboxes based on passed params router.get('/:data', function(req, res, next) { ...

What steps should I take to resolve the "Module Not Found" issue that occurs when I use the command "npm start" after setting up a new React project with npm?

Just starting out with React.js and npm and encountered an issue. After using the command: npm create react-app my-test-npm-react-app I waited for the project to be created successfully. However, when I tried running: npm start I received the followin ...

Check if an element possesses a specific property and corresponding value in JavaScript

I was looking to determine if an object has a specific property with a certain value, and wanted to search for it within an array of objects. var test = [{name : "joey", age: 15}, {name: "hell", age: 12}] After testing the code snippet below, I realized ...

Dragging and dropping elements onto the screen is causing them to overlap when trying

I am having trouble merging the drag and drop functionality from Angular Material with resizing in a table. Currently, both features are conflicting and overlapping each other. What I am hoping for is to automatically cancel resizing once drag and drop s ...

A single snippet of JavaScript blocking the loading of another script

I've encountered an issue where the code seems to be conflicting with itself. The top part works fine, but the bottom part doesn't. However, when I remove the top portion, everything works as intended! You can see a working example of both compo ...

Using interfaces for typecasting in TypeScript

Consider the code snippet below: let x = { name: 'John', age: 30 } interface Employee { name:string, } let y:Employee = <Employee>x; console.log(y); //y still have the age property, why What is the reason for TypeScript ov ...

Google charts appear only after the second request, not on the initial one

Utilizing Google charts to visually represent company performance data. The Javascript code I have written is as follows: <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> go ...

How can we prevent and remove extra whitespace characters such as new lines and line feeds in responseText?

I am troubleshooting an ajax script that is calling a php file. The php file is supposed to echo either "yes" or "no", which I intend to use for logical comparisons. However, when trying to compare the responseText in javascript to check if it matches "y ...

Unable to make calls to functions within my JQuery prototype class

When it comes to setting up the behavior for my content_item elements, I use the following approach: $.fn.createContentItem = function() { $(this).selectItem = function() { $(".content_item").removeClass("selected"); $ ...

How to load multiple components simultaneously within a single router-outlet using Angular 2

I have designed a template for the root component of my angular2 app: <main class="main"> <div class="main__container"> <div class="main__left-area"> <router-outlet name="left-zone"></router-outlet> </div&g ...

altering the color of various spans consecutively

I am looking to create a text effect where each alphabet changes color in a wave-like pattern, starting from the left. I have assigned each alphabet a span with classes like span0, span1, and so on. To change the color, I used the following code: for (var ...

A comprehensive tool for testing JavaScript, CSS, HTML, and jQuery code

Currently, I am working on an extension for Google Chrome that consists of multiple .js, .css, and .html files. My coding process involves using Notepad++ as my primary tool. However, I find myself needing to conduct testing at various stages of developm ...

Monitor the input value for any changes in Angular 8 using the listen component

Hey there! I'm currently working with a component that includes the input @Input() userId: number[] = []; to receive a list of user IDs. Specifically, I have integrated this component into another one, such as the news component: <kt-user-post-li ...