Angular Universal ReferenceError - KeyboardEvent is not defined

半世苍凉 提交于 2020-01-30 07:42:07

问题


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' }, 
           ]
}

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

Commands Defined in package.json as :

"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?


回答1:


here you go

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;

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

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



回答2:


Add this line in server.ts

global['KeyboardEvent'] = null;



来源:https://stackoverflow.com/questions/55650575/angular-universal-referenceerror-keyboardevent-is-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!