angular2 svgPanZoom,window 未定义,webpack 问题?

angular2 svgPanZoom, window is not defined, webpack issue?

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

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

但是我似乎无法让它与 angular2 一起工作,window 无法访问。

经过一番研究,我想我必须将 window 填充到 svg-pan-zoom 的 webpack 导出中。也许我不是在寻找正确的东西,但我认为这是 quite 令人惊讶的是,仅仅为了导入第 3 方 javascript 就需要做很多工作。 我能找到的最好线索是:https://github.com/ariutta/svg-pan-zoom/issues/207 编辑:查看答案。

我用了这个angular 2 aspnet core启动项目: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 但是分支在我做这个的时候更新了 post 这让我很困惑


我这里有这项服务,

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');
        }
    }
}


我的 app.module

中引用了 SvgPanZoomService 服务

我的 package.json 中引用了 Svg-pan-zoom 库,

最后我的 build 给了我 2 个 js 文件,main-client.js 和 vendor.js

我可以浏览 main-client.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_modules\svg-pan-zoom\dist\svg-pan-zoom.js:1493:8

现在我读到我不打算从组件访问 window,但我对 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 个文件 boot-client 和 boot-server 与 webpack.config.js 相关,它们是服务器和客户端文件打包的说明。

谢谢。

这有效

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

When building Universal components in Angular 2 there are a few things to keep in mind. window, document, navigator, and other browser types - do not exist on the server - so using them, or any library that uses them (jQuery for example) will not work. You do have some options, if you truly need some of this functionality:

If you need to use them, consider limiting them to only your client and wrapping them situationally. You can use the Object injected using the PLATFORM_ID token to check whether the current platform is browser or server.

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 调用 window 不存在服务器端。

可以通过在 webpack.config

中添加如下部分来实现这种分离
    module: {
        rules:
        [{test: /svg-pan-zoom/,loader: 'null-loader'}]
    }

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

分离捆绑包后,确保每次调用可能需要 windowdocumentnavigator 的脚本时,我遇到了 [=19] 的问题=] 同样,在 if (isPlatformBrowser(this.platformId)) { //your code } 块中


编辑现在一切都很好:现在我开始工作了我仍然会把它保存在这里,因为当我不知道如何使任何事情工作时它让我精神振奋。 webpack 与我以前见过的所有东西都非常不同,我只是懒得阅读文档,但它们确实存在,而且最终它是一个非常强大的工具,可以完成任务。不同之处在于,如果您不使用服务器端呈现,添加元标记和描述等功能将不会在服务器时间执行。例如,我相信 angular2 应用程序被 google 爬虫视为客户端 javascript,因此不会被加载,使您的 SEO 努力变得毫无价值。


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

How can I disable Universal / SSR (Server-side rendering)?

Simply comment out the logic within HomeController, and replace @Html.Raw(ViewData["SpaHtml"]) with just your applications root AppComponent tag ("app" in our case): .

You could also remove any isPlatformBrowser/etc logic, and delete the boot-server, browser-app.module & server-app.module files, just make sure your boot-client file points to app.module.