briston82
briston82

Reputation: 57

How can I use imports with a specific condition?

I'm relatively new to angular & typescript.

My idea is, to redirect different hostnames to only one angular6 project because most of the stuff is the same, only the language & URLs differ.

E.g. what I have done in app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import {enRoutes} from "lang/en/routes";
import {esRoutes} from "lang/es/routes";
import {frRoutes} from "lang/fr/routes";

let routes: Routes;

switch(window.location.hostname) {
  case 'foobar.es' : {
    routes = esRoutes;
  }
  case 'foobar.fr' : {
    routes = frRoutes;
  }
  default : {
    routes = enRoutes;
  }
}

@NgModule({
    exports: [ RouterModule ],
    imports: [ RouterModule.forRoot(routes) ],
})
export class AppRoutingModule {}

It works like a charm, but the problem I face now is that the routes for each hostName are in the main.js for each of them. Now the Route-Files are really big, also there are more than just 3 hostNames, so the main.js gets really big because of this.

Because of these static imports, it will load all routes, no matter with which hostName it gets called. I tried already lazy loading with import(...).then(...) but it didn't work :(

Has anyone an idea, how to solve this?

Upvotes: 2

Views: 67

Answers (1)

danday74
danday74

Reputation: 56946

The approach to what you are doing seems very wrong.

only the language & urls differ

This should be a single app that serves up the correct language using Angular internationalisation. Angular provide a guide on internationalisation when catering for different languages here ... https://angular.io/guide/i18n

With regards different URLs, what is stopping you just using a simple lookup like this:

[
  {
    "domain": "domainone.com",
    "url": "/url/one/"
  {,
  {
    "domain": "domaintwo.com",
    "url": "/url/two/"
  {
]

If you really need to pursue the lazy loading route (which isn't a bad thing either way) then the Angular docs for lazy loading routes are here:

https://angular.io/guide/lazy-loading-ngmodules

Upvotes: 1

Related Questions