首页 > 解决方案 > 打字稿角度中的参数化导入

问题描述

打字稿中是否提供参数化导入?我正在尝试执行以下操作:

  1. 在我的环境文件中,我指定了程序。
  2. 我想根据活动的程序在我的角度模块中导入文件/组件,如下所示:
/* 
The idea here is that I have a component in two different folders example:

 - /root/components/page-not-found/bingo/page-not-found-component.ts
 - /root/components/page-not-found/pepsi/page-not-found-component.ts
In my environment file I can specify the program as 'bingo' or 'pepsi' which are the folder names and I want to load the component either from 'bingo' directory or from the 'pepsi' directory.
*/

import { environment } from '../environments/environment';
import { PageNotFoundComponent } `./root/components/page-not-found/${environment.program}/page-not-found-component`; // here environment.program refers to the folder name.

@NgModule({
  declarations: [
    PageNotFoundComponent
  ]
});

我尝试了以下但没有成功:

@NgModule({
  declarations: [
    PageNotFoundComponent: (() => import(`./root/components/page-not-found/${environment.program}/page-not-found-component`).then((m) => m.PageNotFoundComponent))()
  ]
});

有什么东西可以使用 javascript/typescript 来实现吗?

标签: typescript

解决方案


不完全是您正在寻找的东西,但我有一个不同方法的建议。

我认为您可以在组件内创建一个块,并从那里根据环境*if加载所需的块。PageNotFoundComopnent

PageNotFoundComoponent html

<page-not-found-component-dev *ngIf="mode==='dev'"></page-not-found-component-dev>
<page-not-found-component-prod *ngIf="mode==='prod'"></page-not-found-component-dev>

PageNotFound 组件 ts

import { environment } from '../environments/environment';
import { PageNotFoundComponentDev } `./root/components/page-not-found-dev/page-not-found-component-dev`;
import { PageNotFoundComponentProd } `./root/components/page-not-found-prod/page-not-found-component-prod`;

@Component({
...
})
export class PageNotFoundComoponent {

 mode = 'dev';
 constructor(){
  mode = environment.mode;
 }

}

推荐阅读