问题描述
我有一个使用开放层 5.3 的 angular 7.2 应用程序.我正在尝试为此应用程序设置 angular 通用,但是当我运行通用服务器 (node dist/server.js
) 时,由于未定义仅客户端变量,我遇到了一些错误,例如作为 window
.
I've got an angular 7.2 app using open layers 5.3. I'm trying to set up angular universal for this app, but when I run the universal server (node dist/server.js
), I got some errors due to client only variables not being defined, such as window
.
webpack:///./node_modules/ol/has.js?:54
var DEVICE_PIXEL_RATIO = window.devicePixelRatio || 1;
^
ReferenceError: window is not defined
我尝试使用 domino 来模拟这些变量,但由于画布元素而失败并出现另一个错误
I tried using domino to mock these variables, but it just fails with another error, because of a canvas element
Error: NotYetImplemented
at HTMLCanvasElement.exports.nyi (/my/project/dist/server.js)
所有 OL 代码都导入并在单个 MapComponent
组件中使用.我的导入在这个组件中看起来像这样:
All the OL code is imported and used in a single MapComponent
component. My imports look like this in this component:
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/Tile.js';
我的主要问题是提到的错误会在我运行通用服务器后立即发生,因此甚至在尝试在浏览器中访问通用呈现的网站之前.
My main problem is that the mentionned errors occur as soon as I run the universal server, so even before trying to access the universal rendered website in a browser.
因此,当应用程序在客户端运行时,使用这样的方法仅实例化 MapComponent
不起作用,因为崩溃发生在此之前
Consequently, using something like this to only instantiate MapComponent
when the app is running client side does not work, since the crash occurs before that
<app-map *ngIf="isBrowser"></app-map>
其中 isBrowser
变量在组件中使用 isPlatformmBrowser(platformId)
where the isBrowser
variabled is initialised in the component with the value of isPlatformmBrowser(platformId)
有什么建议吗?
推荐答案
我遇到的错误是由 pixelworks
库引起的,它是 OL 5 的依赖项.
The error I had was caused by the pixelworks
library, which is a dependency of OL 5.
这个库实例化一个画布并尝试从中获取二维上下文,domino
This library instantiates a canvas and tries to get a 2d context from it, which is not supported by domino
var context = document.createElement('canvas').getContext('2d');
上下文不会立即使用,而是在始终实例化的地方创建.
The context is not used straight away, but is created at a place where it is always instantiated.
由于我不想在服务端执行代码时使用OL,所以我的解决方案是在构建过程中修改server.js
文件,去掉这个实例化.
Since I do not want to use OL when the code is executed server side, my solution was to modify the server.js
file during the build process to remove this instantiation.
sed -i "s/var context = document.createElement('canvas').getContext('2d');/var context = null;/" dist/server.js
注意:domino
还是需要的,因为OL导出的模块也会尝试访问全局变量,比如window
Note: domino
is still needed because the modules exported from OL also try to access global variables, such as window
这篇关于在 Openlayers 5 中使用 angular 7 Universal的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!