为什么我不能在 React 代码中使用 @azure/web-pubsub 节点包?

Why I cannot use the @azure/web-pubsub node package in a react code?

我在 react/webpack 应用程序中导入以下包:

import { WebPubSubServiceClient } from '@azure/web-pubsub'

当我按如下方式调用 WebPubSubServiceClient 时:

const connectionString = 'XXXXX'
const hubName = 'YYYY'
let serviceClient = new WebPubSubServiceClient(connectionString, hubName)

我收到以下错误:

An error occured as follows:  TypeError: url__WEBPACK_IMPORTED_MODULE_1__.URL is not a constructor
    at parseConnectionString (parseConnectionString.js:24)
    at new WebPubSubServiceClient (hubClient.js:31)

通过查看位于 Microsoft @azure/web-pubsub 节点包代码中的调试器中的代码,我发现导入 URL 可能是问题所在:

import { AzureKeyCredential } from "@azure/core-auth";
import { URL } from "url";
export function parseConnectionString(conn) {
    let parsed = {};
    conn.split(";").forEach((i) => {
        const assignmentPos = i.indexOf("=");
        if (assignmentPos === -1)
            return;
        const key = i.substring(0, assignmentPos).toLowerCase();
        const value = i.substring(assignmentPos + 1);
        parsed[key] = value;
    });
    let endpointPart = parsed["endpoint"];
    if (!endpointPart)
        throw new TypeError("connection string missing endpoint");
    if (!endpointPart.startsWith("http")) {
        endpointPart = `https://${endpointPart}`;
    }
    const key = parsed["accesskey"];
    if (!key)
        throw new TypeError("connection string missing access key");
    const credential = new AzureKeyCredential(key);
    const port = parsed["port"];
  >>  const url = new URL(endpointPart); << the error comes from here
    url.port = port;
    const endpoint = url.toString();
    url.port = "";
    return { credential, endpoint };
}
//# sourceMappingURL=parseConnectionString.js.map

关于Webpack我使用的是以下版本:

"webpack": "^4.44.2",
"webpack-bundle-analyzer": "^3.9.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0",

我必须说在纯 nodeJS 中使用相同的代码和模块效果很好。 所以我认为它与反应有关?

我该怎么办?

@azure/web-pubsub 的最新版本应该已经删除了“URL”依赖项。用 https://github.com/Azure/azure-sdk-for-js/pull/15300

修复

最后,运行 只要选择正确的构造函数,React 就很轻松。

所以这里是如何做到的:

// == Azure WebPuSub
import { WebPubSubServiceClient, AzureKeyCredential } from '@azure/web-pubsub'

// == W3C sockets
import { w3cwebsocket as W3CWebSocket } from 'websocket'




// == Create the service client
const hubName = 'telemetry'
const key = <KEY>
const cred = new AzureKeyCredential(key)
const endpoint = "https://XXXXX.webpubsub.azure.com"
const serviceClient = new WebPubSubServiceClient(endpoint, cred, hubName)
console.log('Azure WebPubSub service client is', serviceClient)

/**
 * @summary Connect to the secure socket server thru the WebPubSub service
 */
async function connect ({onError, onOpen, onMessage, onClose}) {
    console.log('About to get auth token…')
    let token = await serviceClient.getAuthenticationToken()
    //console.log('Auth token is', token)
    
    // == Connect to the secured socket server          
    const url = token.url
    let wsClient = new W3CWebSocket(url)

    console.log('Web socket is',wsClient)


    // == Connect the callbacks
    wsClient.onerror = onError
    wsClient.onopen = onOpen
    wsClient.onmessage = onMessage
    wsClient.onclose = onClose
}

// == Now actually connect to the secure web sockets
connect({onError, onOpen, onMessage, onClose})

瞧!像魅力一样工作