【问题标题】:angular2 svgPanZoom, window is not defined, webpack issue?angular2 svgPanZoom,未定义窗口,webpack 问题?
【发布时间】:2017-08-25 13:21:25
【问题描述】:

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

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

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

经过一些研究,我认为我必须将窗口填充到 svg-pan-zoom 的 webpack 导出中。也许我不是在寻找正确的东西,但我认为这是非常惊人的,有这么多的工作需要完成,只是为了导入一个 3rd 方 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 但是在我发这个帖子的时候分支已经更新了,这让我很困惑


我这里有这个服务,

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 库,

最后,我的构建给了我 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

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

谢谢。

【问题讨论】:

    标签: angular webpack asp.net-core angular2-universal svgpanzoom


    【解决方案1】:

    这行得通

    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 库的引用,在此case 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,我也遇到了localStorage的问题,在if (isPlatformBrowser(this.platformId)) { //your code }里面块


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


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

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

    只需注释掉 HomeController 中的逻辑,并替换 @Html.Raw(ViewData["SpaHtml"]) 仅包含您的应用程序根目录 AppComponent 标签(在我们的例子中是“app”):.

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

    【讨论】:

    • 最后你想通了。很棒
    猜你喜欢
    • 1970-01-01
    • 2018-08-13
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多