Does anyone know how to retrieve the application version or import the package.json file? Can't seem to find the solution on

I need to display the version from the package.json file in my Angular application.

To import it, I allowed importing json by adding a few extra lines in tsconfig.json:

{
  "compilerOptions": {      
    "module": "commonjs",
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "moduleResolution": "node"
  }
}

Even after making these changes, when I try to import the json file in my component class:

import { myPackage } from '../../../package.json';

I still encounter this error:

Cannot find module '../../../package.json'. Consider using '--resolveJsonModule' to import modules with '.json' extension.ts(2732)

The issue is not with the path as I have tried putting another simple json file in the same folder and encountered the same error.

Despite researching and following examples related to '--resolveJsonModule', it seems like I have done everything correctly... but it just doesn't work.

I have also restarted VScode and the angular service, but it hasn't resolved the problem.

I am currently using Angular 10.0.11 and TS 3.9.7

Please provide guidance! Thank you!

Answer №1

If you want to retrieve the information from package.json in angular, there are 3 key steps you need to follow:

  1. In your tsconfig.json, make sure to enable the resolveJsonModule option within the compilerOptions section as shown below:
    compilerOptions": {
         ......
         "resolveJsonModule": true
         ......
    }
  1. Once you have done that, run npm start in your terminal.

  2. After running npm start, you will be able to access all the variables from package.json inside your component like this:

import * as  packageJson from 'package.json';
......
export class AppComponent {
      ......
      version = packageJson.version;
      ......
}

Answer №2

Although Deepak's answer was close to being correct, it unfortunately did not solve my issue. Fortunately, a related answer () provided helpful comments that guided me in the right direction.

In my specific situation, my Angular application required more than just modifications to tsconfig.json in order to import JSON files successfully. I had to make adjustments to other 'flavours' such as base, spec, and app, each serving its own purpose. To ensure the import worked within components under test, it was necessary to include it in 'spec', but ultimately it was cleaner to include it in 'base'.

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

Ensure the modal is closed when the user clicks on the Finish button within Docusign

I have a Docusign sign URL displayed in an iframe on my webpage. When the user clicks on FINISH, I want to close the modal iframe instead of redirecting to another page within the iframe. Please refer to the screenshot below for more clarity: I am implem ...

The integration of ngx-translate with an HTTP interceptor is currently experiencing difficulties

Using ngxtranslate for application translation has been seamless so far. However, I am facing an issue with the HttpInterceptor. This interceptor attempts to retrieve data from local storage at the start and displays a dialog prompting you to either load t ...

Achieving the desired type of value within a nested record

I am trying to create a unique function that can manipulate values of a nested Record, based on the collection name. However, in my current implementation, I am facing difficulty in attaining the value type: type Player = { name:string } type Point = { x:n ...

How to retrieve cookie value from callback response in Angular?

There are two domains: Angular Application: samlapp.domain.com Node Application: samlapi.domain.com When Node calls the callback with the cookie, it redirects to the samlapp application (samlapp.domain.com/landing) Concern: How can I retrieve the cook ...

Maintain the URL state while logging in using angular-oauth2-oidc

In our Angular application, we utilize angular-oauth2-oidc for authentication management with the Code Flow and PKCE. To enable automatic login for users upon app visit, we initialize our app as follows: this.oauthService.configure(authModuleObject); this. ...

Converting JSON to a std::string in C++ retrieved from a URL

Is there a simple method to fetch JSON data from a URL link and convert it into a std::string in a C++ file? I'm looking to implement this functionality and would appreciate any guidance or advice on how to achieve this. ...

Understanding JSON: Pairing Keys with Values

Is it possible to match the keys with the corresponding values in a JSON file? Check out this JSON file here View an image of the data structure I am referencing The keys are located in the "fields" section, while the values can be found in the "data" s ...

How can I restart an asynchronous observable when the parameter changes?

My async observable is designed to take 2 parameters for calculation purposes: public preferredCurrency: string = ''; wmData$ = this.http.get<any>("./api/wealthModeling/GetWMData"); portfolioCalculation$ = this.wmData$.pipe ...

Is there a way to dynamically create a property and assign a value to it on the fly?

When retrieving data from my API, I receive two arrays - one comprising column names and the other containing corresponding data. In order to utilize ag-grid effectively, it is necessary to map these columns to properties of a class. For instance, if ther ...

Is it possible for gson and retrofit to return null when trying to fetch dynamic JSON data

I am struggling with a dynamic JSON that contains nested objects. I have created POJOs for this data, but the model always appears as NULL and I can't figure out what I did wrong. Here is the JSON snippet: { "status": 200, "message": "Accept ...

How can we exclude fields from JSON.stringify in type-graphql entities?

Utilizing https://github.com/MichalLytek/type-graphql for crafting our graphql schema has posed a challenge. When we serialize the TypeScript entity object, it does not adhere to the field annotations in our GQL entities, resulting in unwanted data leakage ...

Is there a way to incorporate an external JavaScript file into a .ts file without the need for conversion?

I have an external JavaScript file that I need to utilize in a .ts file without performing any conversion. Does anyone know how to use it within TypeScript without the need for conversion? ...

Tips for implementing an if else statement in ReactJS while utilizing the useEffect hook

Below is the code snippet for returning a Plotly graph. I would like to display a message or alternative layout when there is no data available for the graph, such as showing "No data available". How can I achieve this? import React, { useEffect } from ...

What steps do I need to take to activate the legacy policy API for Google login?

The Legacy People API has not been utilized in project 145315848075 or it is currently disabled. To enable it, please go to and then attempt again. If you have recently activated this API, please wait a few minutes for the changes to take effect before ...

Creating a JSON object with an array using MySQL

Just a quick question for you... I'm working with a database that has two tables : Articles (id, content, title, date) Comments (id_article, username, content) I am trying to generate a JSON array structured like this : [ { "id": "5785634a ...

Attempt to resend HTTP requests using Angular Interceptor exclusively upon user's manual action of clicking a button

I have implemented the Angular HttpInterceptor to handle errors in my Http requests. When an error occurs, except for 401, I show a popup modal with two buttons ('Close' and 'Retry'). However, I am struggling to understand how to retry ...

Converting files to base64 before uploading them in Angular

I am facing an issue with uploading files from an Angular 4 app to a JSON API service that requires base64 strings as file content. My approach involves reading the file using FileReader.readAsDataURL, and upon user confirmation for upload, I create a JSO ...

TypeScript does not verify keys within array objects

I am dealing with an issue where my TypeScript does not flag errors when I break an object in an array. The column object is being used for a Knex query. type Test = { id: string; startDate: string; percentDebitCard: number, } const column = { ...

Verify if the date surpasses the current date and time of 17:30

Given a date and time parameters, I am interested in determining whether that date/time is greater than the current date at 17:30. I am hoping to achieve this using moment js. Do you think it's possible? This is what I have been attempting: let ref ...

How can you test an Action method in ASP.Net MVC that accepts an Array of Objects and returns a JsonResult?

I'm currently working on setting up a unit test within a Visual C# Unit Test project. My goal is to pass in an empty Array of Frame class and have it return a JSON object. [HttpPost] public JsonResult SubmitBowlingScore(Frame[] frames) { ...