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

Using Typescript to implement an onclick function in a React JS component

In my React JS application, I am using the following code: <button onClick={tes} type="button">click</button> This is the tes function that I'm utilizing: const tes = (id: string) => { console.log(id) } When hovering ov ...

Creating a unique custom error message for every validation option

I am using a Joi schema and I would like to set custom error messages for each validation option. Here is an example of my schema: const schema = Joi.object().keys({ name: Joi.string() .min(5).error(() => 'first message') .ma ...

Steps for creating a jasmine test suite

I'm currently creating a unit test for Angular2 using Jasmine. Below is the code snippet I am working with: component.ts toggleSelect() { this.checked = event.target.checked this.tree.forEach(t => { t.checked = this.checked }) ...

Angular: Exploring the Dynamic Loading of a Component from a String Declaration

Is there a way to compile a component defined by a string and have it render in a template while still being able to bind the click event handler? I attempted to use DomSanitizer: this.sanitizer.bypassSecurityTrustHtml(parsedLinksString); However, this a ...

Issue: setAllcategories function not found

Currently engaged in using Next.js and Sanity as a Headless CMS for the backend. In the code snippet below, I have created a Categories.js file in the components folder to fetch some data. My objective is to extract all the titles from the category Array. ...

How can I update an image source using JavaScript in a Django project?

Is it possible to dynamically change the image src using onclick without relying on hard paths or Django template tags? I have concerns that this may not be best practice. How can I implement a method to inject/change the ""{% static 'indv_proj&b ...

Is there a way for me to update a Link To containing a parameter by using history.push with a parameter inside a table cell?

Hey there! I'm working on some code and wondering if it's doable to replace the Link To with a history.push, including the following parameter, like so: <TableCell style={{width: '10%'}}> <Link to={`/run-id/${item.run_ ...

Choose the option in real-time with Jquery

I'm currently developing a dynamic HTML for Select Option as seen below: item += "<td class='ddl' style='width:40%;'>"; item += "<select>" item += " <option id='list' name='selector' value=" + se ...

An effective way to retrieve a property from an observable by utilizing a pipe

I'm having trouble storing an OrderState object in my ngrx store and extracting data from it for my UI using the async pipe. Specifically, I want to retrieve a child property from this observable object. order.state.ts export interface OrderState { ...

Navigate the array and divide the elements into separate values

For a project I need to upload files, wherein the data is organized within an object like [5.76516834507, 50.8474898368], [5.76115833641, 50.8453698247]. The task here is to extract and store the first value as latitude: 5.76516834507 and the second value ...

Sharing State with a Secure Route in Vue Router (using the script setup method)

Hello everyone, I'm encountering an issue while trying to send a state to the protected routes in vue-router. The error that I faced mentioned "Discarded invalid param(s) "_id", "dish_name", "description", "img" ...

Unable to retrieve content using the query.ID in Next.js

I'm trying to figure out what is causing the issue in this code, but I can't seem to resolve it. My goal is to use the query.id inside getInitialProps to fetch some content. The fetching process works fine, but when an error occurs, I receive thi ...

How do I extract elements from an array?

I'm working with an array of objects: var aoo = [{},{},{},....{},{},{}]; I am looking for an efficient function that can retrieve elements from index n to m. For example: var getEl = function(from, to) { ... return array } What is the best way to ...

Eliminate pipe operators from RXJS Observables

I am facing a challenge where I need to modify the operators applied to an observable by removing or adding new ones. Here's the scenario: Suppose I have the following immutable observable: let objects$ = of([{ category: 1, name: 'S ...

Exploring the realm of variable scope in JavaScript and Vue.JS

I am a newcomer to JavaScript and I have encountered an issue with the scope of my object/variable. Can you please help me understand why my {endtoken:this.token} is empty, while console.log({rawToken:e.data}) is not? I find the concept of variable scope ...

Fetching a JSON object from an external URL using JavaScript

Currently, I am working on a project using JavaScript and have an API that provides me with a JSON Object. You can access this JSON object by clicking on the following link: . Within this JSON object, there is a specific element located at JSONOBJECT.posi ...

Issues may arise in Typescript when trying to return an array of data from a redux createAsyncThunk function

Below is the code I am using to retrieve a list of users: export const fetchUserById = createAsyncThunk( "users/fetchById", async (_, { rejectWithValue, fulfillWithValue }) => { try { const response = await fetch(`https://reqres. ...

Mask the "null" data in JSON

I'm currently working with a JSON file and trying to display it in a bootstrap table. Check out the code snippet I've been using: $(document).ready(function(){ $.getJSON(url, function(data){ content = '<h1><p class="p1 ...

angucomplete-alto automatically fills in data based on another input

Having two autocomplete select boxes with a unique feature has been quite interesting. The first input accepts a code that is related to a label, autofilling the second input with the corresponding object once the code is selected in the first input. Howev ...

Is it possible for clients to view my .env variable value?

I store all my private API keys, like the one for Google Maps, in a .env file. I've been told that with React JS, the JavaScript code runs on the client side. Does this mean that my .env variables, including my API keys, are accessible to clients who ...