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?
3
Answers
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.
To make your mock component support [(ngModel)] binding use this tutorial. http://almerosteyn.com/2016/04/linkup-custom-control-to-ngcontrol-ngmodel
An alternative solution for module imports that does not require dynamic script loading: you can use the
compilerOptions.paths
option in your server app’stsconfig.json
file to redirect the imported module to a server-only version:When the server app builds, the compiler will import the server module instead of the browser module.
I want to answer too. This is my solution.
You need create three environments as here:
then in angular.json in build section spoofing files for browser:
and for server:
so anywere we can use a variable environment.isServer
if something is unclear, you can see an example here sourse