簡體   English   中英

Webpack添加jQuery插件:錯誤:jQuery需要帶有文檔的窗口

[英]Webpack adding jQuery plugin: Error: jQuery requires a window with a document

我正在使用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次,錯誤消失了。 謝謝你的幫助!

正如您在上一個問題的評論中所說,您無法在服務器端通過服務器端預渲染來運行依賴於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替換my-app的選擇器,通常是模板中的app

或者,您必須有條件地運行代碼,如本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
}

以避免在服務器端預渲染上運行此類代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM