question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[bug] CoinbaseWalletSDK is not a constructor error on development env using vite

See original GitHub issue

Is there an existing issue for this?

  • I have searched the existing issues

Package Version

0.3.1

Current Behavior

Can’t use CoinbaseWalletConnector with Vitejs on development.

image

image

Expected Behavior

It shouldn’t give error on development env.

Steps To Reproduce

create a vite react-ts app. After that:

package.json:

{
  "name": "wagmitestvite",
  "private": true,
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "ethers": "^5.6.4",
    "lodash-es": "^4.17.21",
    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "util": "^0.12.4",
    "wagmi": "^0.3.1"
  },
  "devDependencies": {
    "@esbuild-plugins/node-globals-polyfill": "^0.1.1",
    "@types/react": "^18.0.0",
    "@types/react-dom": "^18.0.0",
    "@vitejs/plugin-react": "^1.3.0",
    "typescript": "^4.6.3",
    "vite": "^2.9.5"
  }
}

vite.config.ts:

import {defineConfig} from 'vite'
import react from '@vitejs/plugin-react'
import NodeGlobalsPolyfillPlugin from "@esbuild-plugins/node-globals-polyfill";

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [react()],
    optimizeDeps: {
        esbuildOptions: {
            // Node.js global to browser globalThis
            define: {
                global: 'globalThis',
            },
            // Enable esbuild polyfill plugins
            plugins: [
                NodeGlobalsPolyfillPlugin({
                    buffer: true
                })
            ]
        }
    }
})

tsconfig.json:

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": false,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": ["./src"]
}

main.tsx:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import {InjectedConnector} from 'wagmi/connectors/injected'
import {WalletConnectConnector} from 'wagmi/connectors/walletConnect'
import {CoinbaseWalletConnector} from 'wagmi/connectors/coinbaseWallet'
import {Chain, createClient as createWagmiClient, WagmiProvider} from 'wagmi';
import {getDefaultProvider, providers} from "ethers";

const chains = [
    {
        id: 56,
        name: 'Binance Smart Chain',
        nativeCurrency: {
            name: 'BNB',
            symbol: 'BNB',
            decimals: 18,
        },
        rpcUrls: {
            default: 'https://bsc-dataseed.binance.org',
            default2: "https://bsc-dataseed1.defibit.io/",
            default3: "https://bsc-dataseed1.ninicoin.io/"
        },
        blockExplorers: {
            etherscan: {
                name: 'BNB Smart Chain Explorer',
                url: 'https://bscscan.com'
            },
            default: {
                name: 'BNB Smart Chain Explorer',
                url: 'https://bscscan.com'
            }
        }
    }
]

export const coinbaseWalletConnector = ({chainId}: { chainId?: number | undefined }) => new CoinbaseWalletConnector({
    chains,
    options: {
        appName: "wagmi",
        chainId: chainId,
        jsonRpcUrl: "https://bsc-dataseed.binance.org"
    }
});

export const injectedConnector = new InjectedConnector({
    chains,
    options: {
        shimDisconnect: true
    }
});

export const walletConnectConnector = ({chainId}: { chainId?: number | undefined }) => new WalletConnectConnector({
    chains,
    options: {
        chainId,
        qrcode: true,
    },
})

const connectors = (config: { chainId?: number | undefined }) => {
    return [
        injectedConnector,
        coinbaseWalletConnector(config),
        walletConnectConnector(config)
    ]
}

const provider = ({chainId}: { chainId?: number | undefined }): any => {
    if (!chainId) return getDefaultProvider();
    const chain = chains.find((tempChain) => tempChain.id === chainId) as Chain;
    const providerUrl = chain.rpcUrls.default;

    const jsonRpcProvider = new providers.JsonRpcProvider(providerUrl, chainId);

    return jsonRpcProvider
}

const wagmiClient = createWagmiClient({
    autoConnect: true,
    connectors,
    provider
});


ReactDOM.createRoot(document.getElementById('root')!).render(
    <React.StrictMode>
        <WagmiProvider client={wagmiClient}>
            <App/>
        </WagmiProvider>
    </React.StrictMode>
)

App.tsx:

import React from 'react';
import './App.css';
import {useAccount, useBalance, useConnect} from "wagmi";

function Balance() {
    const {data: account, isError: isErrorAccount, isLoading: isErrorLoading} = useAccount()
    const {data: balance, isError: isErrorBalance, isLoading: isLoadingBalance} = useBalance({
        addressOrName: account?.address,
    })

    if (isErrorLoading) return <div>Loading account…</div>
    if (isErrorAccount) return <div>Error loading account</div>

    if (isLoadingBalance) return <div>Fetching balance…</div>
    if (isErrorBalance) return <div>Error fetching balance</div>

    return (
        <div>
            <b>Account:</b> {account?.address}
            <br/>
            <b>Balance:</b> {balance?.formatted}
        </div>
    )
}

function App() {
    const {connect, isConnected, connectors} = useConnect();

    return (
        <div className="App">
            <header className="App-header">
                {
                    connectors.map(connector => (
                        <button key={connector.id} onClick={() => connect(connector)}>{connector.name} CONNECT</button>
                    ))
                }
                {isConnected && <Balance/>}
            </header>
        </div>
    );
}

export default App;

Link to Minimal Reproducible Example (CodeSandbox, StackBlitz, etc.)

No response

Anything else?

It might happen because of using pnpm as package manager, idk

Issue Analytics

  • State:closed
  • Created a year ago
  • Reactions:2
  • Comments:10 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
cesargdmcommented, May 18, 2022

@tmm @jcheese1 @ilterugur

For some wired reason, vite is making a nested default export for Coinbase. Tried using yarn, pnpm and npm and all fail. So I would guess that Vite is the issue.

If I try to import the module directly in my app there’s not double default.

Screen Shot 2022-05-17 at 7 11 01 PM

Left, import directly in app. Right, current module


Screen Shot 2022-05-17 at 7 13 22 PM

Notice the property default repeated twice with the raw import without accessing default first. If I access the default property twice, the connector works.


1reaction
tmmcommented, May 18, 2022
Read more comments on GitHub >

github_iconTop Results From Across the Web

[bug] CoinbaseWalletSDK is not a constructor error on ...
It shouldn't give error on development env. Steps To Reproduce. create a vite react-ts app. After that: package.json: { "name": ...
Read more >
vue.js - Vite production build errors: `...is not a constructor' for ...
I'm trying to do a build for a simple Vue-based project with Vite, but I am running into an error when actually processing...
Read more >
global is not defined aws-sdk - You.com | The AI Search ...
I'm testing an Angular 6 app with AWS Cognito and noticed an error in my ... Describe the bug Customers using the Amplify...
Read more >
Env Variables and Modes - Vite
You may see errors like Missing Semicolon or Unexpected token in this case, for example when "process.env. NODE_ENV" is transformed to ""development": "...
Read more >
Handling process.env - Quasar Framework
quasar/app-vite) How to differentiate the runtime procedure based on ... You might be getting process is not defined errors in the browser console...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found