【问题标题】:Angular 9 and SSR - window is not definedAngular 9 和 SSR - 未定义窗口
【发布时间】:2020-09-13 02:22:15
【问题描述】:

我正在使用 Angular 9 和 SSR,但其中一个包出现错误。

const DragEvevent = window.DragEvent

ReferenceError: window is not defined

ngx-chips 包上

我们已经尝试将变量添加到 nodeJs 中:

const domino = require('domino');
const fs = require('fs');
const template = fs.readFileSync(join(join(process.cwd(), 'dist/emaua-front/browser'), 'index.html')).toString();
console.log(template);
const win = domino.createWindow(template);

// mock
global['window'] = win;
global['document'] = win.document;
global['DOMTokenList'] = win.DOMTokenList;
global['Node'] = win.Node;
global['Text'] = win.Text;
global['HTMLElement'] = win.HTMLElement;
global['navigator'] = win.navigator;

但错误仍然存​​在。

更新

After updating all packages I got the error: 
ERROR in multi ./src/assets/css/ripple.min.scss ./src/assets/css/lounge.scss ./src/assets/css/discovery.scss ./src/assets/css/main.scss ./src/styles.scss ./node_modules/roboto-fontface/css/roboto/roboto-fontface.css ./node_modules/material-design-icons/iconfont/material-icons.css ./node_modules/bootstrap/dist/css/bootstrap.min.css ./node_modules/bootstrap/dist/css/bootstrap-theme.min.css ./node_modules/ng-bootstrap-to-bootstrap-3/dist/ng-bootstrap-to-bootstrap-3.min.css ./node_modules/jquery-ui-dist/jquery-ui.min.css ./node_modules/jquery-ui-dist/jquery-ui.theme.min.css ./node_modules/ag-grid-community/dist/styles/ag-grid.css ./node_modules/ag-grid-community/dist/styles/ag-theme-balham.css ./node_modules/slick-carousel/slick/slick.scss ./node_modules/slick-carousel/slick/slick-theme.scss ./src/assets/css/animate.css ./node_modules/cookieconsent/build/cookieconsent.min.css
Module not found: Error: Can't resolve '/Users/vinh/learning/front-end/node_modules/bootstrap/dist/css/bootstrap-theme.min.css' in '/Users/vinh/learning/front-end'
this.debug is not a function

之后我按照here 中的说明应用了修复

我又遇到了同样的错误:

const DragEvent = window.DragEvent;
                  ^

ReferenceError: window is not defined

ngx-chips 包上

更新

我们在 ngx-chips 中遇到的问题是以前发生的。

https://github.com/Gbuomprisco/ngx-chips/issues/740 https://github.com/Gbuomprisco/ngx-chips/issues/786

有人知道解决这个问题的方法吗?

【问题讨论】:

  • 你可以试试这样 const DragEvent = (window as any).DragEvent
  • 您所拥有的不应导致该错误。哪个模块导致了问题?另外,只是检查一下,您是否确保添加多米诺骨牌后应用程序编译正确,并重新启动 node/pm2 进程?这有时发生在我身上,我没有调试最新版本的代码......
  • @David 我更新了模块并尝试重新启动进程,但仍然是同样的问题。

标签: node.js angular angular-universal angular9


【解决方案1】:

我升级到 Angular 10,我在服务器上的 ngx-chips 遇到了同样的问题。

我解决了这个问题如下: 我可能和很多人一样,在服务器上渲染时并不需要这个组件。 懒得创建一个单独的项目来排除这个模块。 所以我只是禁用了这个组件。

在模板中:

<div *ngIf="isBrowser()">
   <tag-input [(ngModel)]=...  
   </tag-input>
</div>

在打字稿中:

isBrowser() {
  if (window) {
       return true;
  }
  return false;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 2019-01-26
    • 2021-09-07
    • 2021-08-11
    • 2019-11-07
    相关资源
    最近更新 更多