【问题标题】:Webpack adding jQuery plugin: Error: jQuery requires a window with a documentWebpack 添加 jQuery 插件:错误:jQuery 需要一个带有文档的窗口
【发布时间】:2017-10-30 10:35:27
【问题描述】:

我正在使用 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
];

启动应用程序时出现此错误:

NodeInvocationException:由于错误,预渲染失败:错误: jQuery 需要一个带有文档的窗口

如果我刷新页面 2-3 次,错误就消失了。 感谢您的帮助!

【问题讨论】:

  • 你想达到什么目的?您希望能够在您的应用程序中使用 jquery 吗?
  • 嗨。我想在 Angular 4 +webapck 应用程序中使用 Mottie Virtual keryboard jquey 插件。Jquery 已包含并且似乎正在工作。谢谢

标签: jquery angular angular-webpack-starter


【解决方案1】:

正如您在previous question 的 cmets 中所说,您无法通过服务器端预渲染在服务器端运行依赖于 window 和其他一些情况(如会话存储)的 javascript 代码。

ASP.NET Core Angular Web 模板等模板带有服务器端渲染启用。这适用于不需要会话存储、身份验证或访问浏览器组件或 dom-tree 的应用程序。

您必须通过从Index.cshtml 中删除asp-prerender-module="ClientApp/dist/app.module.server.ts" 标签助手来禁用服务器端预呈现。

替换

<my-app asp-prerender-module="ClientApp/dist/app.module.server.ts"></my-app>

<my-app></my-app>

当然,将my-app 替换为您的应用程序的选择器,通常是模板中的app

或者你必须有条件地运行代码,正如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
}

避免在服务器端预渲染上运行此类代码。

【讨论】:

  • 暂时错误消失。我会继续测试。谢谢
猜你喜欢
  • 2017-08-29
  • 2014-02-16
  • 1970-01-01
  • 2017-10-22
  • 2019-10-21
  • 2017-07-30
  • 2013-12-21
  • 2020-08-19
  • 2018-07-05
相关资源
最近更新 更多