angular2 svgPanZoom,窗口未定义,webpack 问题



我想在我的网站上实现一个显示SVG图像的缩放功能。

我看到了这个库github.com/ariutta/svg-pan-zoom它提供了我需要的确切功能,

但是我似乎无法让它与 angular2 一起使用,窗口无法访问。

经过一些研究,我认为我必须将窗口填充到 Webpack 导出中以进行 SVG-Pan-Zoom。也许我不是在寻找正确的东西,但我认为非常令人惊讶的是,仅仅导入第三方 javascript 就需要做很多工作。 我能找到的最好的线索是这个: https://github.com/ariutta/svg-pan-zoom/issues/207 编辑:见答案。

我使用了这个角度 2 aspnet 核心启动项目: https://damienbod.com/2017/01/01/building-production-ready-angular-apps-with-visual-studio-and-asp-net-core/

编辑:实际上是这个 https://github.com/MarkPieszak/aspnetcore-angular2-universal 但是在我发布这篇文章时,分支得到了更新,这让我感到困惑


我这里有这项服务,

svg-pan-zoom.service.ts

import { Injectable } from '@angular/core'
import { isBrowser } from 'angular2-universal';
import * as svgPanZoom from 'svg-pan-zoom';
@Injectable()
export class SvgPanZoomService {
getPanZoom(element: any) {
if (isBrowser) {
svgPanZoom(element);
}
}
}

这里叫 map.component.ts

import { Component, AfterViewInit } from '@angular/core';
import { SvgPanZoomService } from '../../injectables/svg-pan-zoom.service';
import { isBrowser } from 'angular2-universal';
@Component({
selector: 'map-full',
template: require('./map.component.html'),
styles: [require('./map.component.css')]
})
export class MapComponent implements AfterViewInit {
constructor(private svgZoom: SvgPanZoomService) {
if (isBrowser) {
this.svgZoom.getPanZoom('#evSvgMap');
}
}
}


SvgPanZoomService 服务在我的应用程序中被引用。

Svg-pan-zoom lib 在我的 package.json 中被引用,

最后,我的构建给了我 2 个 js 文件,主客户端.js和供应商.js

我可以浏览主客户端.js并看到它引用了 svg-pan-zoom,
当我的页面加载
时,它存在于我的浏览器源中

但是当涉及到加载它应该做事的部分时,我收到此错误。

An unhandled exception occurred while processing the request.
Exception: Call to Node module failed with error: 
Prerendering failed because of error: ReferenceError: window is not defined
at D:[mystuff]node_modulessvg-pan-zoomdistsvg-pan-zoom.js:1493:8

现在我读到我不打算从组件访问窗口,但我对 lib 调用的内容没有发言权,我在这里的某个地方读到添加(isBrowser)应该验证我是否不调用这个服务器端(为什么我希望服务器缩放这是 UI 对吗?

这是我的webpack.config.js

var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var nodeExternals = require('webpack-node-externals');
var merge = require('webpack-merge');
var allFilenamesExceptJavaScript = /.(?!js(?|$))([^.]+(?|$))/;
// Configuration in common to both client-side and server-side bundles
var sharedConfig = {
resolve: { extensions: [ '', '.js', '.ts' ] },
output: {
filename: '[name].js',
publicPath: '/dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
loaders: [
{ test: /.ts$/, include: /ClientApp/, loader: 'ts', query: { silent: true } },
{ test: /.html$/, loader: 'raw' },
{ test: /.css$/, loader: 'to-string!css' },
{ test: /.(png|jpg|jpeg|gif|svg)$/, loader: 'url', query: { limit: 25000 } }
]
}
};
// Configuration for client-side bundle suitable for running in browsers
var clientBundleConfig = merge(sharedConfig, {
entry: {
'main-client': './ClientApp/boot-client.ts'
},
output: { path: path.join(__dirname, './wwwroot/dist') },
devtool: isDevBuild ? 'inline-source-map' : null,
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [] : [
// Plugins that apply in production builds only
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin()
])
});
// Configuration for server-side (prerendering) bundle suitable for running in Node
var serverBundleConfig = merge(sharedConfig, {
entry: { 'main-server': './ClientApp/boot-server.ts' },
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, './ClientApp/dist')
},
target: 'node',
devtool: 'inline-source-map',
externals: [nodeExternals({ whitelist: [allFilenamesExceptJavaScript] })] // Don't bundle .js files from node_modules
});
module.exports = [clientBundleConfig, serverBundleConfig];

然后,应用程序加载另一个 webpack.config.vendor.js

var isDevBuild = process.argv.indexOf('--env.prod') < 0;
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var extractCSS = new ExtractTextPlugin('vendor.css');
module.exports = {
resolve: {
extensions: [ '', '.js' ]
},
module: {
loaders: [
{ test: /.(png|woff|woff2|eot|ttf|svg)(?|$)/, loader: 'url-loader?limit=100000' },
{ test: /.css(?|$)/, loader: extractCSS.extract(['css']) }
{ test: require("svg-pan-zoom"),
loader: "imports-loader?window=>window./svg-pan-zoom.js"} // wild try
]
},
entry: {
vendor: [   
'@angular/common',
'@angular/compiler',
'@angular/core',
'@angular/http',
'@angular/platform-browser',
'@angular/platform-browser-dynamic',
'@angular/router',
'@angular/platform-server',
'angular2-universal',
'angular2-universal-polyfills',
'bootstrap',
'bootstrap/dist/css/bootstrap.css',
'es6-shim',
'es6-promise',
'jquery',
'zone.js',
'svg-pan-zoom' //i added this, no clue if it's relevant.
//EDIT :Turns out it was important, very much so.
]
},
output: {
path: path.join(__dirname, 'wwwroot', 'dist'),
filename: '[name].js',
library: '[name]_[hash]',
},
plugins: [
extractCSS,
new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery'}), // Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DllPlugin({
path: path.join(__dirname, 'wwwroot', 'dist', '[name]-manifest.json'),
name: '[name]_[hash]'
})
].concat(isDevBuild ? [] : [
new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } })
])
};

我还有 2 个与 webpack.config 相关的引导客户端和引导服务器文件.js它们是打包服务器和客户端文件的说明。

谢谢。

这有效

https://github.com/MarkPieszak/aspnetcore-angular2-universal#universal-gotchas

在 Angular 2 中构建通用组件时,有几件事 要记住。windowdocumentnavigator和其他浏览器类型 - 服务器上不存在 - 因此使用它们或任何使用它们的库(例如 jQuery)将不起作用。您确实有一些选择,如果 您确实需要其中一些功能:

如果需要使用它们,请考虑将它们限制为仅客户端 并按情况包装它们。您可以使用注入的对象 检查当前平台是否为浏览器的PLATFORM_ID令牌 或服务器。

import { PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
constructor(@Inject(PLATFORM_ID) private platformId: Object) { ... }
ngOnInit() {
if (isPlatformBrowser(this.platformId)) {
// Client only code.
...
}
if (isPlatformServer(this.platformId)) {
// Server only code.
...
}
}

但是请记住,如果您使用的是 webpack,则需要通过制作两个单独的捆绑包来分离客户端和服务器端代码,服务器端捆绑包不得包含对您正在使用的客户端 JavaScript 库的引用,在这种情况下,svg-pan-zoom 调用窗口不存在服务器端。

这种分离可以通过在 webpack.config 中添加如下部分来实现

module: {
rules:
[{test: /svg-pan-zoom/,loader: 'null-loader'}]
}

此空加载器需要npm install null-loader --save
更多信息:https://github.com/webpack-contrib/null-loader

分离捆绑包后,请确保每次调用可能需要windowdocumentnavigator的脚本,我在 if(isPlatformBrowser(this.platformId)) { //your code }块内也遇到了localStorage问题


现在编辑一切都很好:现在我让它工作了,我仍然会把它放在这里,因为当我无法弄清楚如何使任何事情工作时,它让我精神振奋。 webpack 与我以前看到的所有东西都非常不同,我只是懒得阅读文档,但它们确实存在,最后它是一个非常强大的工具,可以完成工作。不同之处在于,如果不使用服务器端渲染,则添加元标记和描述等功能将不会在服务器时间执行。例如,我相信angular2应用程序被谷歌爬虫视为客户端JavaScript,因此不会被加载,使您的SEO工作毫无价值。


另一个建议是摆脱服务器端渲染功能,我做到了,它适用于这个以及后来出现的任何其他与客户端相关的问题。 https://github.com/MarkPieszak/aspnetcore-angular2-universal#faq---also-check-out-the-faq-issues-label

如何禁用通用/SSR(服务器端渲染)?

只需注释掉 HomeController 中的逻辑,然后替换 @Html.Raw(ViewData["SpaHtml"]) 只包含您的应用程序根目录 AppComponent 标签(在本例中为"app"):。

您还可以删除任何isPlatformBrowser/etc逻辑,并删除 boot-server,browser-app.module & server-app.module 文件,只需制作 确保引导客户端文件指向 app.module。

最新更新