Angular2-starter configuration setup with environment-based variables (such as .env or .conf) for testing and production settings

Frameworks like PHP Laravel often include files for local configuration, separate from dev, test, and production environments. How can a configuration file be provided for an angular-starter project that contains all local environment variable values (such as Google Analytics key, sentry.io, etc.)?

Answer №1

Here is a solution that is compatible with AoT (Ahead of Time Compilation):

To make this work, create a file named .env.example.js in the main directory of your angular-starter project (where you find package.json, docker, and other top-level files). The contents of the file should look like this:

// Copy this file to './.env.js' and modify variables in EnvData

var Env = {
    google_analytics: 'XX-YYYYYYYY-Z',
    sentry_clientKey_publicDSN: 'https://[email protected]/yyyyyy',
    // Add more variables here
};

module.exports = Env;

Copy this file as .env.js and add it to the .gitignore file. Then commit both .env.example.js and .gitignore to your git repository.

We are using .js files instead of .ts (typescript) because webpack works on js files when generating the index.html file. Now, let's see how to use these variables in webpack configuration files. Navigate to ./config/webpack.common.js, find the code snippet below, and add the new line:

  new HtmlWebpackPlugin({
    template: 'src/index.html',
    title: METADATA.title,
    chunksSortMode: 'dependency',
    metadata: METADATA,
    inject: 'head',
    env: require('../.env')    // <-- new line
  }),

In ./src/index.html, update the Google Analytics section like so:

  <% if (htmlWebpackPlugin.options.env.google_analytics) { %>
  <!-- Google Analytics: -->
  <script>
    (function(A,n,g,u,l,a,r){A.GoogleAnalyticsObject=r;A[l]=A[l]||function(){
    (A[l].q=A[l].q||[]).push(arguments)},A[l].l=1*new Date();a=n.createElement(g),
    r=n.getElementsByTagName(g)[0];a.async=1;a.src=u;r.parentNode.insertBefore(a,r)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

    ga('create', '<%= htmlWebpackPlugin.options.env.google_analytics %>', 'auto');
    ga('send', 'pageview');
  </script>
  <% } %>

In your typescript module/component/class (.ts file), you can access variable values by importing the js file. Here's an example for setting up Sentry:

import * as Raven from 'raven-js'; 
import * as Env from '../../.env.js';
...
let sentryDSN = Env['sentry_clientKey_publicDSN']
if(sentryDSN)
{
    Raven.config(sentryDSN).install();
    ...
}
...

That's all for now :)

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

Implement the use of NextAuth to save the session during registration by utilizing the email and password

When registering a user using email, password and username and storing in mongodb, I am looking to incorporate Next Auth to store sessions at the time of registration. My goal is to redirect the user in the same way during registration as they would experi ...

Utilize Protractor to extract the text within a specified span element

Is it possible to check if the text of the span within the button is "Vigente" using expect and Jasmine? If so, how can I achieve this? <button _ngcontent-hke-28="" class="btn btn-success disabled" tabindex="-1"> <span _ngcontent-hke-28="" class= ...

Display images that have been uploaded on the page either as a grid view or a list of

In my Reactjs application, I am uploading multiple images to Azure Blob Storage. On a page, there is a button to open the upload form. Once the upload completes, I want to display all these images on the same page. Since the images have different aspect ...

Exploration Pointers for Foursquare Web Users

Why does my search suggestion keep returning '568 broadway' even after I have updated the authentication to my client id and client secret? Currently running on: https://api.foursquare.com/v2/venues/suggestCompletion?ll=40.7,-74&query=fours ...

Guide on incorporating vanilla JavaScript into a personalized Vue component

I'm currently working on incorporating a basic date-picker into a custom Vue component. Since I am not utilizing webpack, I want to avoid using pre-made .vue components and instead focus on understanding how to incorporate simple JavaScript into Vue. ...

The onclick function fails to function properly following an Ajax reload of the <div> element

I have an issue with my onclick function that only works the first time. Every time the onclick function triggers an ajax request, it successfully reloads a div which contains code to retrieve values from SQL and build an HTML table using a for loop. Alth ...

Handle all link clicks on the webpage

My challenge is that some users are required to utilize a virtual desktop in order to access specific information on my website. However, within the virtual environment, there are links leading to external content that do not function properly. I am seekin ...

Trouble accessing HTML file in web browser

I just finished creating a basic webpage called HelloWorld.html using HTML, JavaScript, and CSS. It runs smoothly when I open it from Eclipse IDE and view it through a browser. The functionality of the page is that it contains 5 buttons, each revealing th ...

Steps for eliminating QRcode warning in npmjs package

Issue: Warning Message (node:24688) ExperimentalWarning: buffer.Blob is an experimental feature. This feature could change at any time (Use `node --trace-warnings ...` to show where the warning was created) Seeking Solution: How can I prevent this warning ...

Instructions for adding and deleting input text boxes on an ASP.NET master page

*I am currently facing an issue with adding and removing input textboxes for a CV form using ASP.NET in a master page. Whenever I click on the icon, it doesn't seem to work as intended. The idea is to have a textbox and an icon "+" to add more textbox ...

Function generation using TypeScript

I'm in the process of creating a tool to automatically generate boilerplate code for me. The concept involves parsing all .json files within a folder called config, and then creating interfaces and auxiliary functions based on that data. Thanks to t ...

Enhancing React Functionality: Increasing React State Following an If Statement

Whenever I click on the start/stop button, it triggers the handlePlay function. This function then proceeds to initiate the playBeat function. In an ideal scenario, the play beat function should continuously display 1222122212221222... until I press the st ...

What is the best way to retrieve a value from a JSON object using AngularJS?

Using nodeJS, the server sends a JSON object to the controller: data = { "question": "theQuestion", "answer": "theAnswer" }; res.json(data); In the controller, I attempt to manipulate the variable as follows: data = QA.get(); $scope.q = data[que ...

How can you tell if a specific keyboard key is being pressed along with the CTRL button?

Is there a way to call functions when a specific key is pressed along with the CTRL key (on a Windows system)? While testing for a particular keyCode, I used event.keyCode. I researched the codes assigned to each key and assumed that 17 + 73 would represe ...

Creating a Music Bingo game to ring in the New Year

Looking to create a Music Bingo game for New Year's Eve with randomized songs that can be selected, but experiencing an issue where nothing happens when you have 4 in a row. Attempted adding a submit button, but it doesn't trigger any action. Ide ...

I'm having trouble figuring out the code for the path in the POST request for my basic login form application

I have built a basic login form application in node.js. Although I can successfully display the login form and input login data, my POST request to capture the login data is not functioning correctly. I am encountering a POST http://localhost:3000/client 4 ...

Using jQuery to trigger a click event on a radio button prevents the button from being checked

Having trouble with using the .trigger("click"); function on radio buttons to activate a button in a form. When I use the code below, the button is triggered as expected. However, it seems to be interfering with the radio button, causing it to appear chec ...

The 401 error code does not provide a JSON response

Here is an example of using Phalcon to create an API: $response = new Response(); $response->setStatusCode( 401, 'Unauthorized' ); $response->setContentType( 'application/json', 'UTF-8' ); $response->setJsonContent( ...

Challenges regarding placement and z-index are causing issues

Currently, I am attempting to make the menu overlap the content on my webpage. However, I am facing an issue where it moves the content box instead of overlapping it. I have already experimented with the position: relative concept, but unfortunately, the ...

How to submit the next row using jQuery AJAX only when the previous submission is successful without using a loop - could a counter

Currently, I am dealing with loops and arrays. My goal is to submit only the table rows that are checked, wait for the success of an Ajax call before submitting the next row. Despite trying various methods, I have not been successful in achieving this yet. ...