Using a configuration file with the JavaScriptServices React-Redux template

I have come across this question many times on different platforms, but I haven't been able to make it work for me. The issue is that I am using an API within a React component (with TypeScript 2.4.1 and webpack 2.5.1):

....
fetch("some/url/api/", method:"POST",...).then(/*some code*/)

My goal is to automatically determine the environment of the app and fetch the correct api depending on whether it's in production or development mode.

After doing some research online, I put together the following code in my webpack.config:

...
var API_URL = {
  production: JSON.stringify('http://some.server.example'),
  development:  JSON.stringify('http://localhost:xxxx')
}

var environment = process.env.NODE_ENV === 'production' ? 'production' : 'development'

...

const sharedConfig = () =>({
  ...
  plugins:[
    ...
    new webpack.DefinePlugin({
      'API_URL': API_URL[environment]  
    })
  ]
});

When I tried calling fetch like this: fetch(API_URL+"api/endpoint"), I received the error message:

Cannot find name 'API_URL'.any

I am wondering if there is something specific I need to import to access the value of API_URL. I assumed it would be globally accessible. Any assistance on this matter would be greatly appreciated.

Answer №1

The reason for this error is that the typescript compiler does not recognize that webpack will be providing the API_URL. Therefore, it is actually functioning correctly by warning you about using a variable that does not exist. However, since you know that the build will supply this variable, you can inform TypeScript of its existence by declaring it first.

declare const API_URL: string
//...
fetch(API_URL + "api/endpoint").then(/* ... */)

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

Configuring Bootstrap 4.3 with Webpack on Rails 6

I've been attempting to integrate Rails 6.0.0 and Bootstrap 4.3 with webpack, following tutorials like this one tutorial1 and this one tutorial2, but haven't had full success yet. Right now, the bootstrap navigation displays a black box when hove ...

Tips for sorting an array with various data types in TypeScript while explicitly defining the type

I need help with a class that contains two fields, each being an array of different types but sharing the common field id. I am trying to create a method that filters the array and removes an item based on the provided id. enum ItemType { VEGETABLES = &a ...

Combine a pair of select statements to utilize the RxJS store within an Angular Guard

When working on an Angular Guard, I encountered a challenge where I needed to select two fields from the ngrx store. Here is the code snippet for reference: @Injectable() export class RoleGuard implements CanActivate { constructor( public router: A ...

Issues with tracking changes in Vue.js when using reactive variables

After triggering a click event, I am attempting to choose a message from a json file. However, I am encountering an issue where the first click does not seem to select anything. Upon the second click, the selected messages are duplicated, and this pattern ...

My component is displaying a warning message that advises to provide a unique "key" prop for each child in a list during rendering

I need help resolving a warning in my react app: Warning: Each child in a list should have a unique "key" prop. Check the render method of `SettingRadioButtonGroup`. See https://reactjs.org/link/warning-keys for more information. at div ...

A guide on defining global TypeScript interfaces within Next.js

In the process of developing an ecommerce web application with next.js and typescript, I found myself declaring similar interfaces across various pages and components. Is there a method to create global interfaces that can be utilized by all elements wit ...

Dealing with the "this" problem in TypeScript and its impact on scope

Here is my code snippet: class MyClass { name = "MyClass"; // traditional method definition getName1(){ return this.name; } // method defined as an arrow function getName2 = () => { return this.name; ...

Sending data from parent component to change MUI Button color (React with typescript)

Recently, I've been integrating MUI (v5) into a create-React-App with typescript. I have a custom theme set up as well. My goal is to develop a MyButton Component that accepts a buttonType prop (of type string), which corresponds to my theme.palette, ...

Converting the 'require' call to an import may be a more efficient method when importing package.json in a typescript file

In my current project, I am creating a class where I am directly accessing the package version number like this: const pkg = require('../package.json') export class MyClass() { constructor() { // Set the base version from package.jso ...

Unusual behavior observed in Angular 2 when handling button click events

In my .ts file, there are two straightforward methods: editLocation(index) {} deleteLocation(index) { this.locations.splice(index, 1); } The corresponding HTML triggers these methods when buttons are clicked: <button (click)="editLocation(i)" ...

What has become of the main template or layout file in this SSR Vue server-side rendering webpack example?

The documentation for ssr vue (server side rendering for vuejs) includes an example of code structure that involves a webpack build step: Here is how the structure appears: src ├── components │ ├── Foo.vue │ ├── Bar.vue │ ...

Converting language into class components using ngx-translate in Angular

Seeking to convert the information from a table into my typescript class. The data in the table is sourced from a JSON file within the /assets directory. Is there a method to accomplish this task? How can I categorize translation within a typescript class ...

Exploring TypeScript in the world of Shopify Command Line Interface

Exploring the process of developing a Shopify app using Typescript starting with the shopify-app-cli boilerplate, which utilizes Koa for the server and Nextjs for the frontend in React JavaScript. see https://github.com/Shopify/shopify-app-cli Encounterin ...

Arranging containers by invoking a function with material UI

I am completely new to material UI, typescript, and react, so if I make any mistakes or use the wrong terms please feel free to correct me. My goal is to place 4 boxes on a page, with three of them in a row and the fourth stacked below the first box. Curr ...

How can you extract the property names of the first object in an array of objects?

I have an array of objects with the following structure and I want to extract the property names of the first object from this array without including the values. The desired result should only be ["Name", "Account", "Status"] ...

When using Angular, receiving a "Bad Request" error message with a status code of 400 after making a POST

I am encountering an issue when trying to send register form data to my server as I keep receiving a (Bad Request) error. Interestingly, the server works correctly when tested with postman using the following data: { "username": "root", "email": " ...

The not-null constraint is violated in the "id" column because of a null value when using Sequelize Typescript

My Database Setup Journey Recently, I embarked on a database adventure where I decided to use Sequelize-Typescript to assist me with all the heavy lifting in terms of database operations. The first step was creating a table called uma_tbl_users, and here ...

Substitute all attributes of objects with a different designation

I need to update all object properties from label to text. Given: [ { "value": "45a8", "label": "45A8", "children": [ { "value": "45a8.ba08", "label": "BA08", &q ...

Strategies for managing common dependencies while distributing components across various applications within a monorepo

In my monorepo, the structure is as follows: root --AppOne ----package.json ----node_modules ------styled-components --AppTwo ----package.json ----node_modules ------styled-components --Shared ----componentA ----package.json ----node_modules ------style ...

Looking to execute a service method within an authguard service?

I am a beginner with Angular and I am looking to invoke a service method within the authguard service. The specific service function that I need is as follows. Please note that I do not want to make any changes to this service function. loadOrganizations() ...