Running nestjs-console commands within an Angular/nx workspace environment can be easily achieved by following these steps

I have integrated a NestJS application within an Angular / Nx workspace environment.

For running commands in the Nest application, I am utilizing nestjs-console (e.g., to load fixture data).

As per the instructions in the nestjs-console documentation, the process involves:

  1. Creation of a console.ts file
  2. Inclusion of a script in package.json like:
    "console:dev": "ts-node --project apps/api/tsconfig.console.json apps/api/src/console.ts"
  3. Execution via command line, e.g., using: npm run console:dev -- --help

My use of Nx has been beneficial for creating a shared code library across applications

While this setup works seamlessly with commands under Angular CLI (such as test or serve), it encounters issues with nestjs-console tasks leading to the error:

Error: Cannot find module '@my-workspace/my-lib'

Therefore, the key question remains on how to bring the nestjs-console command within the purview of Angular CLI (or implement NestJS commands through alternative means).

I believe it should be feasible to incorporate a custom task into angular.json that leverages an existing builder and thereby directs to the console command. While I don’t think a custom builder is necessary, I could be mistaken about this.

The challenge lies in my lack of familiarity with this setting and the workspace configuration in angular.json.

Assistance is welcomed, whether in the form of:

  • Guidance on potential methodologies
  • Sample instances to emulate
  • Specific guidelines

UPDATE

I experimented with using the NestJS Application Context directly (as opposed to relying on nestjs-console) and followed the instructions outlined in this blog post by executing it with ts-node.

Nevertheless, I encountered similar challenges as before. The problem seems related to how ts-node manages paths in tsconfig.

By altering the way shared code is imported from:

import { HeadwordDto } from '@my-workspace/my-lib';

To:

import { HeadwordDto } from '../../../../../../libs/my-lib/src';

Everything functions properly, albeit triggering tslint complaints stating "library imports must start with @my-workspace/ (nx-enforce-module-boundaries)." This contradicts the essence of Nx.

Exploring the path-related issue appears complex and entails tools like tspath or module-alias. Moreover, these solutions do not leverage the advantages of Nx.

Subsequently, I augmented angular.json by introducing a new Architect target similar to the build target (utilizing the @nrwl/node:build builder) specifically tailored towards constructing the desired application context:

"build-console": {
  "builder": "@nrwl/node:build",
  "options": {
    "main": "apps/api/src/console.ts",      // build console application context
    "outputPath": "different/output/path",  // can run alongside app
    ...
  }
},

Once the build is completed, it can be executed via node:

node ./different/output/path/main.js –help

UPDATES CONTINUED...

Expanding further on the previous approach, there's also the option to utilize the execute builder to continuously build the console application context in a separate terminal window:

"serve-console": {
  "builder": "@nrwl/node:execute",
  "options": {
    "buildTarget": "api:build-console",
    "port": 7778,
    "args": ["--help"]
  }
},

Following this progression, the next step could involve transforming the console application context into a distinct app, featuring its own project structure in angular.json, and selectively incorporating the essential code components. It almost appears as though the Nx team is lightyears ahead ;-)

While not certain if this is the optimal resolution, it does seem effective. As always, open to any suggestions!

FURTHER UPDATES

As a response to @Digitrance's query, I settled on the following course of action:

angular.json

{
    ...
    "api": {
      ...
      "architect": {
        ...
        "build-console": {
          "builder": "@nrwl/node:build",
          "options": {
            "outputPath": "dist/apps/api-console",
            "main": "apps/api/src/console.ts",
            "tsConfig": "apps/api/tsconfig.app.json"
          }
        },
        "serve-console": {
          "builder": "@nrwl/node:execute",
          "options": {
            "buildTarget": "api:build-console",
            "port": 7778,
            "args": ["--help"]
          }
        },

/my-repo/apps/api/src/console.ts

import { BootstrapConsole } from 'nestjs-console';
import { AppModule } from './app/app.module';

const bootstrap = new BootstrapConsole({
  module: AppModule,
  useDecorators: true
});
bootstrap.init().then(async app => {
  try {
    await app.init();
    await bootstrap.boot();
    process.exit(0);
  } catch (e) {
    console.error('Error', e);
    process.exit(1);
  }
});

This set up allows for running the console commands using:

ng run api:build-console
ng run api:serve-console

node ./dist/apps/api-console/main.js --help
node ./dist/apps/api-console/main.js myCommand

(Note that api was used as the app name)

Hope this explanation proves helpful!

Answer №1

Just like many others, I faced challenges while trying to set this up. The main issue stemmed from syntax errors, which, as per some discussions on the ts-node GitHub page, were related to Node's inability to properly interpret imports due to commonjs syntax. Here's how I resolved it:

  1. Create a tsconfig.console.json file next to the tsconfig.app.json in your NX application.
  2. Ensure that the tsconfig.console.json includes "module": "commonjs" within the "compilerOptions". Apart from that, I essentially duplicated the contents of tsconfig.app.json.
  3. In the package.json file, add the following script:
    "console:dev": "ts-node --project apps/api/tsconfig.console.json -r tsconfig-paths/register apps/api/src/console.ts"
    .

I hope this solution proves helpful for you or anyone facing similar issues.

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

Recording changes in SVG size in Angular 2

I am aiming to create an SVG canvas within an Angular 2 template that automatically scales with its parent element and triggers a redraw method when its size changes. While using the onresize property, I successfully receive events but encounter difficult ...

Validation of email forms in Angular 5

I have encountered a challenge that I need help with: Using Angular 5 - template driven form In my template, there is an input field with the type email. Here's an example: <input type="email" [(ngModel)]="model.email" #email="ngModel" email /> ...

Setting the sidebar width for Nebular with two sidebars in the layout: A step-by-step guide

Having two sidebars (identified as left and right) in my page layout, I initially set both sidebars to a width of 400px using the custom theme method with sidebar-width: 400px. However, I now need to change the width of the right sidebar to 700px. Is the ...

Oops! Make sure to explicitly allow the dependency @types/html2canvas by adding it to the "allowedNonPeerDependencies" option

After installing the html2canvas package in my Angular library project, I encountered an error when compiling in production mode using the command ng build --prod. The specific error message is as follows: ERROR: Dependency @types/html2canvas must be exp ...

Expanding Angular FormGroup Models with TypeScript

I've developed a foundational model that serves as a base for several other form groups. export class BaseResource { isActive: FormControl; number: FormControl; name: FormControl; type: FormControl; constructor( { ...

Navigating Routes with Router in Angular 7: A Step-by-Step Guide

Within my sidebar navigation component, the sidebar.component.html file is structured as follows: <nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top" id="sideNav"> <a class="navbar-brand" href="#page-top"> <span cl ...

Setting up OpenID configuration in angular-oauth2-oidc to bypass authentication for certain addresses

In my Angular project, I implemented OpenID authentication using the angular-oauth2-oidc project. However, I need to disable authentication for certain routes. To achieve this, I start the code flow in the main component and bootstrap it in the main modu ...

Replicate the process of transferring table rows to the clipboard, but exclusively copying the contents

Currently, I am attempting to copy a paginated table to my clipboard by referring to this guide: Select a complete table with Javascript (to be copied to clipboard). However, the issue lies in the fact that it only copies the data from the first page. In ...

Discovering the intricacies of using *ngFor on an object in Angular with Firebase

Tools I'm Utilizing Angular Firebase My Current Setup A component that showcases information about an 'Issue' Within the issue, there is another section called 'images' Under the image node, there are additional properti ...

A guide on capturing the text content of the error message from the <mat-error> element with Protractor

I have encountered an element that is giving me trouble in retrieving the error message text into a variable. <mat-error _ngcontent-c16="" class="mat-error ng-star-inserted" id="error-email-required" role="alert" ...

What is the best method for retrieving information from a Java REST API using Angular 7?

view image descriptionaccess this API link here Can someone explain the process of retrieving data from this api? ...

When a URL is entered, information is not retrieved from the database

I have a simple app setup where the data (iPhones from the database) is fetched in the AppComponent itself. ngOnInit(): void { this.iphoneservice.fetchIphones(); } The fetchIphones method is located in my iPhoneService file and consists of 3 functio ...

Managing form input in Ionic2 components from external sources in Angular2

Hello there, I am currently facing an issue with managing form validation along with proper styling for nested forms. Here's what I'm aiming to achieve: I have a Page that displays Tabs components with four tabs. Each tab represents a separate @ ...

Using webpack to bundle node_modules into your application

I am facing an issue while trying to load some modules like: moment echarts In my package.json file, I have the following versions specified: "echarts": "^3.1.10" "moment": "^2.14.1" However, I am encountering the errors below: VM2282:1 Uncaught Ref ...

An error was encountered at line 52 in the book-list component: TypeError - The 'books' properties are undefined. This project was built using Angular

After attempting several methods, I am struggling to display the books in the desired format. My objective is to showcase products within a specific category, such as: http://localhost:4200/books/category/1. Initially, it worked without specifying a catego ...

SSR Angular application facing compatibility issues with Plotly.js

I'm facing an issue while developing an Angular app with server-side rendering (SSR) related to plotly.js functionality. The error message I encountered is as follows: C:\Users\x\Desktop\Angularapp\ngseo\dist\server ...

Incorporating an additional ion-item alongside the existing one instead of substituting it

I am retrieving a list of questions from an API with pagination. I have a button that triggers a function to load the next page of questions. Instead of replacing the previous page, I want to append the new questions below the existing ones. Here is my cur ...

Conceal the PayPal Button

Currently, I'm facing a challenge where I need to dynamically show or hide a PayPal button based on the status of my switch. The issue is that once the PayPal button is displayed, it remains visible even if the switch is toggled back to credit card pa ...

Is there a way to create a list of languages spoken using Angular?

I am in search of a solution to create a <select> that contains all the language names from around the world. The challenge is, I need this list to be available in multiple languages as well. Currently, I am working with Angular 8 and ngx-translate, ...

methods for extracting JSON key values using an identifier

Is it possible to extract the Type based on both the file number and file volume number? [ { ApplicantPartySiteNumber: "60229", ManufacturerPartySiteNumber: "1095651", FileVolumeNumber: "E312534.2", Type: "Manufacturer", FileNumber ...