问题
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