[英]Webpack adding jQuery plugin: Error: jQuery requires a window with a document
I'm using Angular 4 +webpack.I've added a jQuery plugin to nonTreeShakableModules const in webpack.config.vendor.js: 我正在使用Angular 4 + webpack。我在webpack.config.vendor.js中的nonTreeShakableModules const中添加了一个jQuery插件:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const merge = require('webpack-merge');
const treeShakableModules = [
'@angular/animations',
'@angular/common',
'@angular/compiler',
'@angular/core',
'@angular/forms',
'@angular/http',
'@angular/platform-browser',
'@angular/platform-browser-dynamic',
'@angular/router',
'font-awesome/css/font-awesome.css',
'zone.js',
];
const nonTreeShakableModules = [
'bootstrap',
'bootstrap/dist/css/bootstrap.css',
'es6-promise',
'es6-shim',
'event-source-polyfill',
'jquery',
'virtual-keyboard' //HERE
];
When starting the application I got this error: 启动应用程序时出现此错误:
NodeInvocationException: Prerendering failed because of error: Error: jQuery requires a window with a document
NodeInvocationException:由于错误而导致预渲染失败:错误: jQuery需要一个带有文档的窗口
If I refresh the page for 2-3 times,error is gone. 如果我刷新页面2-3次,错误消失了。 Thanks for any help!
谢谢你的帮助!
As said in the comments of your previous question , you can't run javascript code which depends on window
and some other cases (like session storage) on the server-side with server-sided pre-rendering. 正如您在上一个问题的评论中所说,您无法在服务器端通过服务器端预渲染来运行依赖于
window
和其他情况(例如会话存储)的javascript代码。
Templates such as ASP.NET Core Angular Web templates comes with server-sided rendering enabled . 诸如ASP.NET Core Angular Web模板之类的模板都启用了服务器端渲染。 This works fine for applications which doesn't require session storage, authentication or access to browser components or dom-tree.
这适用于不需要会话存储,身份验证或访问浏览器组件或dom-tree的应用程序。
You have to disable server-sided prerendering by removing the asp-prerender-module="ClientApp/dist/app.module.server.ts"
tag helper from your Index.cshtml
. 您必须通过从
Index.cshtml
删除asp-prerender-module="ClientApp/dist/app.module.server.ts"
标记助手来禁用服务器端预渲染。
Replace 更换
<my-app asp-prerender-module="ClientApp/dist/app.module.server.ts"></my-app>
with 与
<my-app></my-app>
Of course replace my-app
with the selector of your application, typically app
in templates. 当然,将
my-app
替换my-app
的选择器,通常是模板中的app
。
Alternatively you have to run code conditionally, as pointed in this GitHub issue : 或者,您必须有条件地运行代码,如本GitHub问题所述 :
// boot-client.ts file
import 'ngx-charts';
// some.component.ts
import { isBrowser } from 'angular2-universal';
import * as $ from 'jquery';
// inside ngOnInit
if (isBrowser) {
$('body').hide(); // or whatever call you need to make
}
to avoid running such code on the server-sided pre-rendering. 以避免在服务器端预渲染上运行此类代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.