Include a secondary .ts file in the project that will be compiled into an additional .js file and placed in the dist

Is there a simpler way to tell NX/Angular to compile the app + an extra file separately?

Currently, I have been running 2 npm scripts:

nx build client-extension && npm run client-extension:injector

However, this method creates extra hassle and prevents 'watch' from working properly. I am aware of options like custom webpack configs, but I'm looking for a more straightforward solution.

I have considered exploiting the logic used for Angular worker files, which result in separate .js files. But that approach doesn't seem ideal either.

This is my current project.json configuration:

{
  "name": "client-extension",
  "$schema": "../../node_modules/nx/schemas/project-schema.json",
  "projectType": "application",
  "prefix": "candlejumper",
  "sourceRoot": "apps/client-extension/src",
  "tags": [],
  "targets": {
    "build": {
      "executor": "@angular-devkit/build-angular:application",
      "outputs": ["{options.outputPath}"],
      "options": {
        "outputPath": "dist/apps/client-extension",
        "index": "apps/client-extension/src/index.html",
        "browser": "apps/client-extension/src/main.ts",
        "polyfills": ["zone.js"],
        "tsConfig": "apps/client-extension/tsconfig.app.json",
        "inlineStyleLanguage": "scss",
        "assets": ["apps/client-extension/src/favicon.ico", "apps/client-extension/src/assets", "apps/client-extension/src/manifest.json"],
        "styles": ["apps/client-extension/src/style/styles.scss"]
      },

In essence, I would like to enhance the project.json with an option like:

{
  "extraFiles": ["./my-second-entry.ts"]
}

Answer №1

The styles and scripts section of the angular.json file provides more than just plain strings. It allows you to specify which bundles should be generated by @angular-devkit/build-angular:browser, and whether they should be immediately loaded in the index.html.

"build": {
  ...
  "options": {
    "outputPath": "dist/xxx",
    "index": "xxx/src/index.html",
    "main": "xxx/src/main.ts",
    "polyfills": "xxx/src/polyfills.ts",
    "tsConfig": "xxx/tsconfig.app.json",
    "inlineStyleLanguage": "scss",
    "assets": [
      "xxx/src/favicon.ico",
      "xxx/src/assets",
      "xxx/src/web.config"
    ],
    "styles": [
      "xxx/src/styles.scss",
      {
        "input": "xxx/src/styles/solarized-dark",
        "inject": false,
        "bundleName": "solarized-dark"
      }
    ],
    "scripts": [
      "xxx/scripts/some-script.js",
      {
        "input": "xxx/scripts/path/to/some-typescript.ts",
        "bundleName": "other-scripts",
        "inject": true
      }
    ]
  },
  ...
}

Check out a demo showcasing this feature with the commit that implements it.

Demo:

https://i.sstatic.net/Ox1U6.png https://i.sstatic.net/o0J85.png

You'll notice that you can omit the file extension (css/js) in the bundleName field.

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

Creating and setting a selected option dynamically in Angular 2 for editing purposes

As I attempt to modify a user, I encounter a scenario where the user possesses a non-primitive array of machines. During editing, my goal is to generate new elements with select options and assign the selected value based on the user object: export class ...

Error: Unable to access the 'clearAsyncValidators' property as it is undefined when running Jest tests on an Angular component

Encountering an Error While Testing Components with Jest Here is my code block for onClickLogin() method: onClickLogin() { if(this.loginForm.valid) { this.api.getLoginData().subscribe(res => { const user = res.find(a => { ...

Utilizing Next.js App Router to Enable Static Site Generation for Dynamic Routes in Live Environments

For my portfolio, I am utilizing Next.js's new App Router to highlight projects with dynamic routing (src/app/projects/[id]/page.tsx). During development, useSearchParams is able to correctly retrieve the project ID. However, in production, it returns ...

Turn off the ability to select months in PrimeNG Calendar using Typescript

In my Angular 7 project, I am utilizing PrimeNG Calendar and I am looking to disable the month navigator at the component level based on certain conditions. For example, if the current month is February, I want to disable the month navigator after March. ...

Delete element from the array upon removal from the AutoComplete component

I am facing a challenge with the Material UI AutoComplete component in my project. The issue arises when I try to update the state of the associateList after clearing a TextField. Additionally, I would appreciate any guidance on how to handle removing an ...

Transmit data to a modal popup in Angular 8

Here is the code snippet written in .ts file: openFormModal(id: number) { console.log(id); const modalRef = this.modalService.open(PartidoComponent); modalRef.componentInstance.id = id; //modalRef.componentInstance.id = id; modalRef.r ...

Retrieve the variable only once a response has been received from the POST request

Is there a way to update a variable in my component only after receiving a response from a POST request? Here is the code in component.ts: formSubmit() { this.sent = this.submitProvider.sendByPost(this.form); this.formSent = this.submitProvider.f ...

The Discriminate Union is ineffective in handling function arguments

Trying to create a discriminate union type for two potential component props, but encountering issues with passing the argument to the onClick function in this instance: type TLink = { label: string, onClick?: (e: React.MouseEvent<HTMLAnchorElement& ...

main.js:1 ERROR TypeError: Unable to access property 'querySelectorAll' of null

I am currently using Chartist in conjunction with Angular to generate charts. However, I am encountering a problem where the charts do not display when the server is running, and an error appears on the console. Strangely enough, refreshing the page caus ...

Installing Angular 4 in Visual Studio 2017

Looking to build an Angular web application using Visual Studio 2017. Starting with a new project by selecting Asp.net Web application with Empty template. Feeling unsure about which files need to be copied/included in the project based on the attached sc ...

What is the process for reading a TS file and dynamically updating code with fs in Node.js?

Currently, I am setting up a new project using the Yeoman generator. It successfully creates all the necessary directories and installs dependencies. However, after generating the files, my next step is to update a JavaScript class to match the appName. In ...

Utilize a dynamically defined union type to create a versatile callback function

I'm currently working on creating a message subscription function. A basic version without types is shown below: function createMessage(message) { postMessage(message) } function addSubscriber(messageType, callback) { handleNewMessage(message =&g ...

I recently installed Angular version 12, but another unexpected version 13 was also installed simultaneously. I only wanted version 12, so now I need to figure out how to uninstall

C:\Users\eaind>npm install -g @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96f5faffd6a7a4b8a6b8a4">[email protected]</a> https://i.sstatic.net/LQPPT.png Upon installing version 12 in the direc ...

What is the best way to incorporate an interface in TypeScript with a specific attribute?

I recently came across the Vue3 reactive library code. However, I am not well-versed in TypeScript and unsure how to implement interfaces like the one below: export interface ReactiveEffect<T = any> { (): T _isEffect: true id: number } It appe ...

Maximizing Performance of JSON.stringify in Angular

In my Angular app, I have a service that retrieves JSON data from an API. At times, this API sends back over 400 records (JSON Objects). When I directly access the endpoint in my browser, it takes around 5 seconds to load all the JSON data onto the page. ...

Is it possible to access the service and 'self' directly from the HTML template?

When working with Angular 6, one method to access component properties from a service is to pass 'self' to the service directly from the component. An example of this implementation is shown below: myComponent.ts public myButton; constructor(p ...

Encountering a "Missing Access" error on the Discord.js API when trying to register my slash commands

Three years ago, I created a small Discord bot in Typescript that is now present on over 80 guilds. Recently, I made the decision to update it from discord.js-v12.3.1-dev to discord.js-v13.6, while also integrating the popular slash commands feature. Howe ...

send the user to a different HTML page within an Angular application

Does anyone have the answer to my question? I need help figuring out where the comment is located that will redirect me to another page if it's false. <ng-container *ngIf="!loginService.verificarToken(); else postLogin"> <ul clas ...

Why won't my fetch API function properly in my Next.js project?

import { GetServerSideProps } from 'next'; type Product = { //Product variables id: number; title: string; price: number; thumbnail: string; }; interface ProductsProps { products: Product[]; } export default function Products({ produ ...

Generating a type definition from a JavaScript file

Looking to convert a .js file to a d.ts file, I've noticed that most resources on this topic are from 2 years ago How do you produce a .d.ts "typings" definition file from an existing JavaScript library? My question is, after 2 years, is there a simp ...