I want to pass some basic configuration to the external / third party module. This basic configuration is in JSON file so that it can be easily modify for different environment without rebuilding the code.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MyTestModule } from '@my-test-module';
import { AppComponent } from './app.component';
// I want to eliminate this require statement
const myConstant = require('./someConfigs.json');
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
MyTestModule.forRoot(myConstant.appCode)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Here i want to pass the appcode
to the @my-test-module
. But the only way which i found is using require
statement which is not good in case of tree shaking. Do anyone knows better solution for this?
FIRST/DIRTY SOLUTION
You can basically use declare var myConstant
.
It tells your compiler that the variable exists somewhere so it doesn't thrown any error while compiling.
You then load a js file initializing myConstant
in your index.html <head>
(it has to be loaded BEFORE all your app js) tag from whatever source is convenient for you ie a remote server via a <script>
tag.
Example :
config.js
hosted on your server :
var myConstant = {appCode : whateverYouWant }
Loaded on your app in the head tag :
<script src="//yourserver.com/config.js"></script>
Used in your component like this :
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MyTestModule } from '@my-test-module';
import { AppComponent } from './app.component';
declare var myConstant;
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
MyTestModule.forRoot(myConstant.appCode)
],
providers: [],
bootstrap: [AppComponent]
})
SECOND/CLEANER SOLUTION
Use environment.ts
and environment.prod.ts
files into a "/src/environment"
folder that contains variables for each environments.
An example :
environment.prod.ts
export const environment = {
production: true,
appCode: WHATEVERYOUWANT
};
Loaded into your component like this :
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MyTestModule } from '@my-test-module';
import { AppComponent } from './app.component';
import {environment} from "./environments/environment"
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
MyTestModule.forRoot(environment.appCode)
],
providers: [],
bootstrap: [AppComponent]
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.