是否可以根据条件导入模块?仅当角度2通用应用程序在浏览器中呈现而不在服务器中呈现时,才特定导入外部模块。
此问题与某些依赖于浏览器功能的PrimeNG模块相关,并且只能在浏览器中呈现。在服务器渲染中省略它们会很棒,因为日历和其他组件对SEO来说并不重要。
目前,如果关闭服务器渲染,我可以渲染Calendar组件。但是当我在app.module.ts中包含以下代码并启用服务器渲染时,服务器会在button.js中生成错误“ReferenceError:Event not defined”。
import { CalendarModule } from 'primeng/components/calendar/calendar';
@NgModule({
...
imports: [
...,
CalendarModule
]
})
有一个isBrowser条件由angular提供。
import { isBrowser } from 'angular2-universal';
但我不知道如何将它用于条件导入。有没有办法为模块做到这一点?
因此,有一种方法可以在浏览器中呈现PrimeNG组件,并在服务器呈现时省略它们。这些问题帮助我开始挖掘正确的方向:
angular-cli: Conditional Imports using an environment variable
How can I conditionally import an ES6 module?
在服务器渲染时,我使用了模拟组件来呈现简单的输入字段并使用相同的选择器“p-calendar”。我在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
})
要使模拟组件支持[(ngModel)]绑定,请使用本教程。 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;
}
}
模块导入的替代解决方案,不需要动态脚本加载:您可以在服务器应用程序的compilerOptions.paths
文件中使用tsconfig.json
选项将导入的模块重定向到仅服务器版本:
{
...
"compilerOptions": {
...
"paths": {
"path/to/browser/module": "path/to/server/module"
}
}
}
当服务器应用程序构建时,编译器将导入服务器模块而不是浏览器模块。