Nathan Tamez
Nathan Tamez

Reputation: 83

Can't import Vonage Client SDK into my preact (vite) project

I have a Preact project using Vite. I want to use the nexmo-client SDK from vonage but when I import using the ES method it breaks my project.

// app.tsx
import NexmoClient from 'nexmo-client';

I get the following error in the console.

index.js:19 Uncaught ReferenceError: global is not defined
    at index.js:19:19
    at index.js:12:22
    at node_modules/nexmo-client/dist/index.js (index.js:16:1)
    at __require (chunk-J43GMYXM.js?v=f3505250:11:50)
    at dep:nexmo-client:1:16

However if I import it using via a script tag it works just fine.

// index.html
<script src="node_modules/nexmo-client/dist/nexmoClient.js"></script>

// app.tsx
const NexmoClient = window.NexmoClient;

Upvotes: 1

Views: 319

Answers (1)

Nathan Tamez
Nathan Tamez

Reputation: 83

OK, there are two problems here.

Firstly, NexmoClient tries to use global which is not available on the browser.

Secondly, NexmoClient has a dependency on socket.io-client, for some reason Vite imports a Node version of the socket.io-client that again tries to use modules that are not available on the browser, namely 'child_process'.

To fix both issues you can provide the following config to Vite, this should make sure the resulting build is compatible with the brother.

// vite.config.js or vite.config.ts

import { defineConfig } from 'vite'
import preact from '@preact/preset-vite'

export default defineConfig({
  plugins: [preact()],
  define: {
    global: {},
  },
  resolve: {
    alias: {
      "xmlhttprequest-ssl": "./node_modules/engine.io-client/lib/xmlhttprequest.js"
    }
  }
})

Upvotes: 1

Related Questions