简体   繁体   中英

Dynamic Path Import - Angular Component

Is there any way to import components, or anything for that matter, in a format like this where there is a conditional which decides which one to use?

import { environment } from '../../environments/environment';

import { NgModule, APP_INITIALIZER } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

if (environment.envName == 'dev')
    import { ListInventoryComponent, ConfirmDeleteDialog } from 'this_local_path';
else
    import { ListInventoryComponent, ConfirmDeleteDialog } from 'this_npm_package_path';

I have local components and modules that I am developing and creating npm packages from, but also would like to be able to test them without changing every reference to it in the code.

You cannot conditionally import components that way. What you should use instead is something called Dynamic imports .

You can read more about it here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

(Plus there are many other guides on the internet about it).

An example would be:

const getDynamicComponent = async (envName) => {
    let dynamicComponent;

    if (envName === 'dev') {
        dynamicComponent = await import('this_local_path');
    } else {
        dynamicComponent = await import('this_npm_package_path');
    }

    return dynamicComponent;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM