angular universal: dynamic imports for browser only

房东的猫 提交于 2020-04-11 03:33:10

问题


Is it possible to import a module based on condition? Specificly import external module only if angular 2 universal app being rendered in browser but not in server.

This question is relevant to some PrimeNG modules that depend on browser features and can be rendered only in browser. It would be great to omit them at server rendering cause calendars and other components are not really important for SEO.

Currently I can render Calendar component if turn off server rendering. But server produces an error 'ReferenceError: Event is not defined' in button.js when I include this code below in my app.module.ts and turn on server rendering.

import { CalendarModule } from 'primeng/components/calendar/calendar';
@NgModule({
    ...
    imports: [
        ...,
        CalendarModule
    ]
})

There is a isBrowser condition provided by angular.

import { isBrowser } from 'angular2-universal';

But I don't know how to use it for conditional imports. Is there really a way to do it for modules?


回答1:


So there is a way to render PrimeNG components in browser and omit them while server rendering. Those questions helped me start digging the right direction:

angular-cli: Conditional Imports using an environment variable

How can I conditionally import an ES6 module?

While server rendering I used mock component that renders a simple input field and uses the same selector 'p-calendar'. The final code I ended up with in my app.module.

...//other imports
import { isBrowser } from 'angular2-universal';

let imports = [
    ... //your modules here
];
let declarations = [
    ... //your declarations here
];

if (isBrowser) {
    let CalendarModule = require('primeng/components/calendar/calendar').CalendarModule;
    imports.push(CalendarModule);
}
else {
    let CalendarMockComponent = require('./components/primeng/calendarmock.component').CalendarMockComponent;
    declarations.push(CalendarMockComponent);
}

@NgModule({
    bootstrap: [AppComponent],
    declarations: declarations,
    providers: [
        ... //your providers here
    ],
    imports: imports
})

To make your mock component support [(ngModel)] binding use this tutorial. http://almerosteyn.com/2016/04/linkup-custom-control-to-ngcontrol-ngmodel

import { Component, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => CalendarMockComponent),
    multi: true
};

@Component({
    selector: 'p-calendar',
    template: '<input type="text" class="form-control"/>',
    providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class CalendarMockComponent implements ControlValueAccessor {

    private innerValue: any = '';

    private onTouchedCallback: () => void = () => {};
    private onChangeCallback: (_: any) => void = () => {};

    //From ControlValueAccessor interface
    writeValue(value: any) {
        if (value !== this.innerValue) {
            this.innerValue = value;
        }
    }

    registerOnChange(fn: any) {
        this.onChangeCallback = fn;
    }

    registerOnTouched(fn: any) {
        this.onTouchedCallback = fn;
    }
}



回答2:


An alternative solution for module imports that does not require dynamic script loading: you can use the compilerOptions.paths option in your server app's tsconfig.json file to redirect the imported module to a server-only version:

{
    ...
    "compilerOptions": {
        ...
        "paths": {
            "path/to/browser/module": "path/to/server/module"
        }
    }
}

When the server app builds, the compiler will import the server module instead of the browser module.




回答3:


I want to answer too. This is my solution. You need create three environments as here:

src/environments/server/environments.ts
src/environments/browser/environments.ts
src/environments/environments.ts

then in angular.json in build section spoofing files for browser:

"configurations": {
        "dev": {
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/browser/environment.ts"
            }
          ]
        },
        "production": {
          ...
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/browser/environment.ts"
            }
          ]
        }
      }

and for server:

"configurations": {
        "dev": {
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/server/environment.ts"
            }
          ]
        },
        "production": {
          ...
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/server/environment.ts"
            }
          ]
        }
      }

so anywere we can use a variable environment.isServer

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

environment.isServer ? MapMockModule : MapModule,

if something is unclear, you can see an example here sourse



来源:https://stackoverflow.com/questions/40751383/angular-universal-dynamic-imports-for-browser-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!