Set up Angular 6 environment variables from .env - javascript

There's an angular 6 project using environment variables from ./project/src/environments/environment.prod.ts
export const environment = {
production: true,
testVar: 'gg',
};
The backend for this project also has env variables in a .env file, so a lot of variable duplicate angular env variables. It would be nice to have something like
export const environment = {
production: true,
testVar: process.env.TEST_VAR
};
, so I didn't have to duplicate variables.
ie
I'd like to parse variables from a .env file and assign their values to angular env variables during typescript compilation on the server.
How can this be done?
Maybe with webpack?
UPDATE
Some clarification. My .env file contains no json. It looks like this:
TEST_VAR=1
UPDATE
Since ng eject is not available for Angular 6, I don't seem to be able to hack into webpack config. Looks like deadend here.
ng eject
Overview
Temporarily disabled.
Ejects your app and output the
proper webpack configuration and scripts.

This question becomes also more and more important, when we want to containerize angular applications.
My research lead me to an idea, where I have to write a little node.js or typescript program, using dotenv for reading .env file and create the environment.ts file at buildtime, before starting ng serve.
You can create entries in the package.json like this:
...
"config": "ts-node set-env.ts",
"server": "npm run config && ng serve"
...
and run it with
npm run server
Here is a good explanation with an example typescript file:
https://medium.com/#ferie/how-to-pass-environment-variables-at-building-time-in-an-angular-application-using-env-files-4ae1a80383c

You can create a config file and populate in Run-time.
1) create a File(app-config.json) in assets folder with your variables
{ "servicesUrl": "https://localhost:8080/api"}
2) create a service (AppConfigService ) to read the file.
#Injectable()
export class AppConfigService {
private appConfig;
constructor (private injector: Injector) { }
loadAppConfig() {
let http = this.injector.get(HttpClient);
return http.get('/assets/app-config.json')
.toPromise()
.then(data => {
this.appConfig = data;
})
}
get config() {
return this.appConfig;
}
3) Next we need to tell our application to execute the loadAppConfig() method of our service.
import { NgModule, APP_INITIALIZER } from '#angular/core';
import { AppConfigService } from './services/app-config.service';
#NgModule({
...,
providers: [
AppConfigService,
{
provide: APP_INITIALIZER,
useFactory: appInitializerFn,
multi: true,
deps: [AppConfigService]
}
],
...
})
export class AppModule { }
4) create a function called "appInitializerFn" to call our service in AppModule (app.module.ts)
const appInitializerFn = (appConfig: AppConfigService) => {
return () => {
return appConfig.loadAppConfig();
}
};
...
#NgModule({
...
})
export class AppModule {}
5) import environment and use it :example
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { AppConfigService } from './services/app-config.service';
#Injectable()
export class DataContextService {
basePath: string;
constructor (private environment: AppConfigService, private http: HttpClient) {
this.basePath = environment.config.servicesBasePath;
}
getNames() {
return this.http.get(this.basePath + '/names/');
}
}
for more information please see:
link

If you want to use variables in build time you could use dotenv
As early as possible in your application, require and configure dotenv.
require('dotenv').config()
Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE. For example:
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

Related

Export an angular element as module

I have created a widget using Angular element successfully, which is working fine in HTML.
But how do I export it as a module so that it can be used in another Angular, React, Vue web applications as well to import import { acmaModule } from package-name instead const acmaModule = require('widge.js')
Angular
export class AppModule {
initWidget(options: any){
console.log('options received', options)
}
constructor(private injector: Injector) {
// Expose Window function
(<any>window).acmeWidget = { initWidget: this.initWidget };
// Survey Widget
const surveyComp: any = createCustomElement(SurveyComponent, { injector: this.injector });
customElements.define('acme-survey', surveyComp);
}
ngDoBootstrap() {}
}
HTML
<html>
....
<script src="../survey-widget.js">
<script>
acmeWidget.initWidget({
test: "Hello world"
})
</script>
....
</html>
You can create an export file and declare the exporting for all modules you want to package for external references in there.
For example, you can add a file export.ts to the src folder and then add something like this to the content of the file, assuming your AppModule is under src\AppModule.ts:
//content of export.ts
export * from './AppModule';
...
then in your ng-package.json file, you need to declare export.ts as entry file there. Something like:
//content of ng-package.json
{
"$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
"dest": "../../dist/<your built package name>",
"lib": {
"entryFile": "src/export.ts"
}
}
then after you build your project, you can run npm publish to create the artifact that you can install through npm and import later. Assuming your project's name is test-project, it will be something like:
ng build test-project --prod
# after build is done:
cd dist/test-project
npm publish
see references for npm publish

How to access method of Project A into Project B in nodejs, i am using nestjs

i have MailEvent class and want to use SendEmail method in client project. i use NPM link to share code for client project. but i can't access this method. how can i access this method in client project. i am using nestJS framework. thanks
#Injectable()
export class MailEvent {
constructor(private eventEmitter: EventEmitter2) {}
// store email details to RabbitMQ
SendEmail() {
amqplib.connect(
'amqp://localhost',
(connectionError, connection) => {
if (connectionError) {
throw connectionError;
}
connection.createChannel((channelError, channel) => {
if (channelError) {
throw channelError;
}
const queue = 'Test_emails_queue';
channel.assertQueue(queue, { durable: false });
channel.sendToQueue(queue, Buffer.from(JSON.stringify(email)));
// create event for sending email
this.eventEmitter.emit('send_email', email);
});
},
);
}
In nestjs we can create a reusable module. Then, this module can be imported to another module. If the module is stored in separated repo, then we can build the module first before installing it to another repo using NPM.
Steps to do:
generate nestjs resource, e.g. MailEventModule on the terminal. It will also create the controller and service class
nest g resource mail-event
export the service via the module file mail-event.module.ts
import { Module } from '#nestjs/common';
import { MailEventService } from './mail-event.service';
#Module({
providers: [MailEventService],
exports: [MailEventService]
})
export class MailEventModule { }
Build the module. It will create a new folder named DIST containing the module ready to be installed in another repo/project
npm run build
upload the mail-event module to npm
install mail-event in the client project using npm command, e.g. npm install mail-event
Import the module to the client project in client-project.module.ts
import { Module } from '#nestjs/common';
import { MailEventModule } from 'mail-event';
#Module({
imports: [MailEventModule]
})
export class ClientProjectModule { }
Add MailEventService as dependency to the client project service in client-project.service.ts
import { Injectable } from '#nestjs/common';
import { MailEventService } from 'mail-event';
#Injectable()
export class ClientProjectService {
constructor(private mailEventService: MailEventService) { }
myFunction() {
this.mailEventService.sendEmail();
}
}
If you have tried this steps, please give us the feedback whether it works or not. Thank you

How to implement JSON Schema Faker with Angular 4 and above

Is it possible to use JSON Schema faker as a third party dependency in Angular. I tried to use the dependency injection to Angular however in the providers I am not able to import jsonSchemaFaker.
angular.json
"scripts": [
"./node_modules/json-schema-faker/dist/json-schema-faker.bundle.min.js"
]
jsonSchemaFaker.service.ts
import { InjectionToken } from '#angular/core';
export const JSF_Token = new InjectionToken ('jsonSchemaFaker');
app.module.ts
providers: [
{ provide: JSF_Token, useValue: jsf }
]
...
declare let jsf: any;
This is what I tried to Inject json schema faker as a dependency in my angular app.. I am getting .. Uncaught ReferenceError: jsf is not defined
That is not how you use npm packages in an angular application.
First off, navigate to the directory of your package.json in your application and install the package:
npm install json-schema-faker
Then, inside your components or your services, use it as such:
// at the top of your file, next to other imports
import jsf from 'json-schema-faker';
// json-schema-faker is now available in the rest of your file as jsf
// you can, for example, have a service method that returns that:
jsf.generate({type: 'string'})
I had to change my providers and the declaration to
providers: [
{ provide: JSF_Token, useValue: JSONSchemaFaker }
]
declare let JSONSchemaFaker: any;
Reason: the global name for JSON Schema Faker mentioned in that library is "JSONSchemaFaker". It was a mistake on my part to declare it as jsf.

Load new modules dynamically in run-time with Angular CLI & Angular 5

Currently I'm working on a project which is being hosted on a clients server. For new 'modules' there is no intention to recompile the entire application. That said, the client wants to update the router/lazy loaded modules in runtime. I've tried several things out but I can't get it to work. I was wondering if any of you knows what I could still try or what I missed.
One thing I noticed, most of the resources I tried, using angular cli, are being bundled into seperate chunks by webpack by default when building the application. Which seems logical as it makes use of the webpack code splitting. but what if the module is not known yet at compile time (but a compiled module is stored somewhere on a server)? The bundling does not work because it can't find the module to import. And Using SystemJS will load up UMD modules whenever found on the system, but are also bundled in a seperate chunk by webpack.
Some resources I already tried;
dynamic-remote-component-loader
module-loading
Loading modules from different server at runtime
How to load dynamic external components into Angular application
Implementing a plugin architecture / plugin system / pluggable framework in Angular 2, 4, 5, 6
Angular 5 - load modules (that are not known at compile time) dynamically at run-time
https://medium.com/#nikolasleblanc/building-an-angular-4-component-library-with-the-angular-cli-and-ng-packagr-53b2ade0701e
Some several other relating this topic.
Some code I already tried and implement, but not working at this time;
Extending router with normal module.ts file
this.router.config.push({
path: "external",
loadChildren: () =>
System.import("./module/external.module").then(
module => module["ExternalModule"],
() => {
throw { loadChunkError: true };
}
)
});
Normal SystemJS Import of UMD bundle
System.import("./external/bundles/external.umd.js").then(modules => {
console.log(modules);
this.compiler.compileModuleAndAllComponentsAsync(modules['External'])
.then(compiled => {
const m = compiled.ngModuleFactory.create(this.injector);
const factory = compiled.componentFactories[0];
const cmp = factory.create(this.injector, [], null, m);
});
});
Import external module, not working with webpack (afaik)
const url = 'https://gist.githubusercontent.com/dianadujing/a7bbbf191349182e1d459286dba0282f/raw/c23281f8c5fabb10ab9d144489316919e4233d11/app.module.ts';
const importer = (url:any) => Observable.fromPromise(System.import(url));
console.log('importer:', importer);
importer(url)
.subscribe((modules) => {
console.log('modules:', modules, modules['AppModule']);
this.cfr = this.compiler
.compileModuleAndAllComponentsSync(modules['AppModule']);
console.log(this.cfr,',', this.cfr.componentFactories[0]);
this.external.createComponent(this.cfr.componentFactories[0], 0);
});
Use SystemJsNgModuleLoader
this.loader.load('app/lazy/lazy.module#LazyModule')
.then((moduleFactory: NgModuleFactory<any>) => {
console.log(moduleFactory);
const entryComponent = (<any>moduleFactory.moduleType).entry;
const moduleRef = moduleFactory.create(this.injector);
const compFactory = moduleRef.componentFactoryResolver
.resolveComponentFactory(entryComponent);
});
Tried loading a module made with rollup
this.http.get(`./myplugin/${metadataFileName}`)
.map(res => res.json())
.map((metadata: PluginMetadata) => {
// create the element to load in the module and factories
const script = document.createElement('script');
script.src = `./myplugin/${factoryFileName}`;
script.onload = () => {
//rollup builds the bundle so it's attached to the window
//object when loaded in
const moduleFactory: NgModuleFactory<any> =
window[metadata.name][metadata.moduleName + factorySuffix];
const moduleRef = moduleFactory.create(this.injector);
//use the entry point token to grab the component type that
//we should be rendering
const compType = moduleRef.injector.get(pluginEntryPointToken);
const compFactory = moduleRef.componentFactoryResolver
.resolveComponentFactory(compType);
// Works perfectly in debug, but when building for production it
// returns an error 'cannot find name Component of undefined'
// Not getting it to work with the router module.
}
document.head.appendChild(script);
}).subscribe();
Example with SystemJsNgModuleLoader only works when the Module is already provided as 'lazy' route in the RouterModule of the app (which turns it into a chunk when built with webpack)
I found a lot of discussion about this topic on StackOverflow here and there and provided solutions seem really good of loading modules/components dynamically if known up front. but none is fitting for our use case of the project. Please let me know what I can still try or dive into.
Thanks!
EDIT: I've found; https://github.com/kirjs/angular-dynamic-module-loading and will give this a try.
UPDATE: I've created a repository with an example of loading modules dynamically using SystemJS (and using Angular 6); https://github.com/lmeijdam/angular-umd-dynamic-example
I was facing the same problem. As far as I understand it until now:
Webpack puts all resources in a bundle and replaces all System.import with __webpack_require__. Therefore, if you want to load a module dynamically at runtime by using SystemJsNgModuleLoader, the loader will search for the module in the bundle. If the module does not exist in the bundle, you will get an error. Webpack is not going to ask the server for that module. This is a problem for us, since we want to load a module that we do not know at build/compile time.
What we need is loader that will load a module for us at runtime (lazy and dynamic). In my example, I am using SystemJS and Angular 6 / CLI.
Install SystemJS: npm install systemjs –save
Add it to angular.json: "scripts": [ "node_modules/systemjs/dist/system.src.js"]
app.component.ts
import { Compiler, Component, Injector, ViewChild, ViewContainerRef } from '#angular/core';
import * as AngularCommon from '#angular/common';
import * as AngularCore from '#angular/core';
declare var SystemJS;
#Component({
selector: 'app-root',
template: '<button (click)="load()">Load</button><ng-container #vc></ng-container>'
})
export class AppComponent {
#ViewChild('vc', {read: ViewContainerRef}) vc;
constructor(private compiler: Compiler,
private injector: Injector) {
}
load() {
// register the modules that we already loaded so that no HTTP request is made
// in my case, the modules are already available in my bundle (bundled by webpack)
SystemJS.set('#angular/core', SystemJS.newModule(AngularCore));
SystemJS.set('#angular/common', SystemJS.newModule(AngularCommon));
// now, import the new module
SystemJS.import('my-dynamic.component.js').then((module) => {
this.compiler.compileModuleAndAllComponentsAsync(module.default)
.then((compiled) => {
let moduleRef = compiled.ngModuleFactory.create(this.injector);
let factory = compiled.componentFactories[0];
if (factory) {
let component = this.vc.createComponent(factory);
let instance = component.instance;
}
});
});
}
}
my-dynamic.component.ts
import { NgModule, Component } from '#angular/core';
import { CommonModule } from '#angular/common';
import { Other } from './other';
#Component({
selector: 'my-dynamic-component',
template: '<h1>Dynamic component</h1><button (click)="LoadMore()">LoadMore</button>'
})
export class MyDynamicComponent {
LoadMore() {
let other = new Other();
other.hello();
}
}
#NgModule({
declarations: [MyDynamicComponent],
imports: [CommonModule],
})
export default class MyDynamicModule {}
other.component.ts
export class Other {
hello() {
console.log("hello");
}
}
As you can see, we can tell SystemJS what modules already exist in our bundle. So we do not need to load them again (SystemJS.set). All other modules that we import in our my-dynamic-component (in this example other) will be requested from the server at runtime.
I've used the https://github.com/kirjs/angular-dynamic-module-loading solution with Angular 6's library support to create an application I shared on Github. Due to company policy it needed to be taken offline. As soon as discussions are over regarding the example project source I will share it on Github!
UPDATE: repo can be found ; https://github.com/lmeijdam/angular-umd-dynamic-example
I have tested in Angular 6, below solution works for dynamically loading a module from an external package or an internal module.
1. If you want to dynamically load a module from a library project or a package:
I have a library project "admin" (or you can use a package) and an application project "app".
In my "admin" library project, I have AdminModule and AdminRoutingModule.
In my "app" project:
a. Make change in tsconfig.app.json:
"compilerOptions": {
"module": "esNext",
},
b. In app-routing.module.ts:
const routes: Routes = [
{
path: 'admin',
loadChildren: async () => {
const a = await import('admin')
return a['AdminModule'];
}
},
{
path: '',
redirectTo: '',
pathMatch: 'full'
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
2. if you want to load a module from the same project.
There are 4 different options:
a. In app-routing.module.ts:
const routes: Routes = [
{
path: 'example',
/* Options 1: Use component */
// component: ExampleComponent, // Load router from component
/* Options 2: Use Angular default lazy load syntax */
loadChildren: './example/example.module#ExampleModule', // lazy load router from module
/* Options 3: Use Module */
// loadChildren: () => ExampleModule, // load router from module
/* Options 4: Use esNext, you need to change tsconfig.app.json */
/*
loadChildren: async () => {
const a = await import('./example/example.module')
return a['ExampleModule'];
}
*/
},
{
path: '',
redirectTo: '',
pathMatch: 'full'
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
``
Do it with angular 6 library and rollup do the trick. I've just experiment with it and i can share standalone angular AOT module with the main app without rebuild last.
In angular library set angularCompilerOptions.skipTemplateCodegen to false and after build library you will get module factory.
After that build an umd module with rollup like this:
rollup dist/plugin/esm2015/lib/plugin.module.ngfactory.js --file src/assets/plugin.module.umd.js --format umd --name plugin
Load text source umd bundle in main app and eval it with module context
Now you can access to ModuleFactory from exports object
Here https://github.com/iwnow/angular-plugin-example you can find how develop plugin with standalone building and AOT
I believe this is possible using SystemJS to load a UMD bundle if you build and run your main application using webpack. I used a solution that uses ng-packagr to build a UMD bundle of the dynamic plugin/addon module. This github demonstrates the procedure described:
https://github.com/nmarra/dynamic-module-loading
Yes, you can lazy load modules using by referring them as modules in the router. Here is an example https://github.com/start-angular/SB-Admin-BS4-Angular-6
First couple all the components that you are using into a single module
Now refer that module in the router and angular will lazy load your module into the view.

Ionic3 / Ionic2+ settings.json file for environment variable configuration [duplicate]

I'm working on an ionic2 project and I need to create a new custom JSON config file. I found some tutorials to create one and access it through http.get but I think it's weird to call it through a get request. I want it in the root folder (where all the config JSONs are) and I open/read the file directly.
I don't know if it's possible, or even recommended ? This is why I'm posting here to have some opinions and solutions :)
Thanks
Personally I don't like the read the config.json file by using the http.get way to handle configuration information, and even though there must be another way to just include and read the json file in your code, since we're using Angular2 and Typescript, why not using classes, interfaces and doing it in a more fancy way?
What I'll show you next may seem more complicated than it should at first (although after reading it you will find it very straightforward and easy to understand), but when I started learning Angular2 I saw an example of how they handled config files in the Dependency Injection guide and I followed that in the apps I've worked on to handle config information (like API endpoints, default values, and so on).
According the docs:
Non-class dependencies
[...]
Applications often define configuration objects with lots of small
facts (like the title of the application or the address of a web API
endpoint) but these configuration objects aren't always instances of a
class.
One solution to choosing a provider token for non-class dependencies
is to define and use an OpaqueToken
So you would need to define a config object with the urls and so on, and then an OpaqueToken to be able to use it when injecting the object with your configuration.
I included all my configuration in the app-config.ts file
// Although the ApplicationConfig interface plays no role in dependency injection,
// it supports typing of the configuration object within the class.
export interface ApplicationConfig {
appName: string;
apiEndpoint: string;
}
// Configuration values for our app
export const MY_CONFIG: ApplicationConfig = {
appName: 'My new App',
apiEndpoint: 'http://www...'
};
// Create a config token to avoid naming conflicts
export const MY_CONFIG_TOKEN = new OpaqueToken('config');
What OpaqueToken is may be confusing at first, but it just a string that will avoid naming conflicts when injecting this object. You can find an amazing post about this here.
Then, you just need to include it in the page you need it like this:
import { NavController } from 'ionic-angular/index';
import { Component, OpaqueToken, Injectable, Inject } from "#angular/core";
// Import the config-related things
import { MY_CONFIG_TOKEN, MY_CONFIG, ApplicationConfig } from 'app-config.ts';
#Component({
templateUrl:"home.html",
providers: [{ provide: MY_CONFIG_TOKEN, useValue: MY_CONFIG }]
})
export class HomePage {
private appName: string;
private endPoint: string;
constructor(#Inject(MY_CONFIG_TOKEN) private config: ApplicationConfig) {
this.appName = config.appName;
this.endPoint = config.apiEndpoint;
}
}
Please notice how to include it in the providers array
providers: [{ provide: MY_CONFIG_TOKEN, useValue: MY_CONFIG }]
And how to tell the injector how it should obtain the instance of the config object
#Inject(MY_CONFIG_TOKEN) config: ApplicationConfig
UPDATE
OpaqueToken has been deprecated since v4.0.0 because it does not support type information, use InjectionToken<?> instead.
So instead of these lines:
import { OpaqueToken } from '#angular/core';
// Create a config token to avoid naming conflicts
export const MY_CONFIG_TOKEN = new OpaqueToken('config');
Now we should use
import { InjectionToken } from '#angular/core';
// Create a config token to avoid naming conflicts
export const MY_CONFIG_TOKEN = new InjectionToken<ApplicationConfig>('config');
After reading and reading different solutions I ended up using this hacky implementation. Hopefully there will be a nice and native solution available soon:
import { NgModule } from '#angular/core';
import { environment as devVariables } from './environment.dev';
import { environment as testVariables } from './environment.test';
import { environment as prodVariables } from './environment.prod';
export function environmentFactory() {
const location = window.location.host;
switch (location) {
case 'www.example.org': {
return prodVariables;
}
case 'test.example.org': {
return testVariables;
}
default: {
return devVariables;
}
}
}
#NgModule({
providers: [
{
provide: 'configuration',
useFactory: environmentFactory
}
]
})
export class EnvironmentsModule {}
and then where ever needed, e.g.:
import { Injectable, Injector, Inject } from '#angular/core';
import { AuthenticationService } from '../authentication';
#Injectable()
export class APIService {
private http: Http;
private apiURL: string;
protected authentication: AuthenticationService;
constructor(
public injector: Injector,
#Inject('configuration') public configuration: any
) {
this.http = injector.get(Http);
this.authentication = injector.get(AuthenticationService);
this.apiURL = configuration.apiURL;
};
...

Categories

Resources