问题描述
我正在使用Angular 4 + webpack.我在webpack.config.vendor.js中的nonTreeShakableModules const中添加了一个jQuery插件:
I'm using Angular 4 +webpack.I've added a jQuery plugin to nonTreeShakableModules const in webpack.config.vendor.js:
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:
如果我刷新页面2-3次,错误消失了.感谢您的帮助!
If I refresh the page for 2-3 times,error is gone.Thanks for any help!
推荐答案
如您的,您将无法运行取决于服务器上window
和其他一些情况(例如会话存储)的javascript代码端与服务器端预渲染.
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.
诸如ASP.NET Core Angular Web模板之类的模板带有启用的服务器端呈现.这适用于不需要会话存储,身份验证或访问浏览器组件或dom-tree的应用程序.
Templates such as ASP.NET Core Angular Web templates comes with server-sided rendering enabled. This works fine for applications which doesn't require session storage, authentication or access to browser components or dom-tree.
您必须通过从Index.cshtml
中删除asp-prerender-module="ClientApp/dist/app.module.server.ts"
标记助手来禁用服务器端预渲染.
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
.
替换
<my-app asp-prerender-module="ClientApp/dist/app.module.server.ts"></my-app>
使用
<my-app></my-app>
当然,请使用应用程序的选择器替换my-app
,通常是模板中的app
.
Of course replace my-app
with the selector of your application, typically app
in templates.
或者,您必须有条件地运行代码,如此GitHub问题:
Alternatively you have to run code conditionally, as pointed in this GitHub issue:
// 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.
这篇关于Webpack添加jQuery插件:错误:jQuery需要带有文档的窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!