Angular Universal ReferenceError-未定义KeyboardEvent

时间:2019-04-12 11:25:09

标签: javascript angular webpack angular-universal universal

我在 server.ts 中添加了“ domino”,甚至将 webpack.server.config.js 更新为:

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”。

我正在终端中运行这些命令

  

$ npm运行build: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"

有人有一个主意,如何摆脱这个错误?

2 个答案:

答案 0 :(得分:0)

你去哪里

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文件中

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

答案 1 :(得分:0)

在server.ts中添加此行

global ['KeyboardEvent'] = null;