本文介绍了Angular Universal ReferenceError - 未定义 KeyboardEvent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我添加了多米诺骨牌"在 server.ts 中,甚至将 webpack.server.config.js 更新为:

I have added "domino" in the server.ts and even updated webpack.server.config.js as :

module: {
    rules: [
              { test: /\.(ts|js)$/, loader: 'regexp-replace-loader', options: { match: { pattern: '\\[(Mouse|Keyboard)Event\\]', flags: 'g' }, replaceWith: '[]', } },
              { test: /\.ts$/, loader: 'ts-loader' },
           ]
}

但仍然出现相同的错误:ReferenceError - KeyboardEvent is not defined".

But still getting the same error : "ReferenceError - KeyboardEvent is not defined".

我在终端中运行这些命令

I am running these commands in terminal

$npm run build:ssr

$npm run serve:ssr

$npm run serve:ssr

package.json 中定义的命令为:

"build:ssr": "npm run build:client-and-server-bundles && npm run webpack:server",
"serve:ssr": "node dist/server.js",
"build:client-and-server-bundles": "ng build --prod && ng run angular.io-example:server",
"webpack:server": "webpack --config webpack.server.config.js --progress --colors"

有人知道如何摆脱这个错误吗?

Does anybody have an idea, how to get rid of this error?

推荐答案

给你

const domino = require('domino');
const fs = require('fs');
const template = fs.readFileSync(join(DIST_FOLDER , 'index.html')).toString();
const win = domino.createWindow(template);
global['window'] = win;
global['Node'] = win.Node;
global['navigator'] = win.navigator;
global['Event'] = win.Event;
global['KeyboardEvent'] = win.Event;
global['MouseEvent'] = win.Event;
global['Event']['prototype'] = win.Event.prototype;
global['document'] = win.document;

将上面的代码放到你的 server.ts 文件中

Put above code into your server.ts file before the line

const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require('./dist/server/main');

这篇关于Angular Universal ReferenceError - 未定义 KeyboardEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 15:45