Unable to access attributes of an object that has not been defined (referencing 'providers')

https://i.sstatic.net/9Ntvd.png

When I try to import web3 version 1.2.11, I am using the following code in TypeScript:

import Web3 from 'web3'

const readonlyProvider = new Web3.providers.HttpProvider(providerURL)

However, after compiling it, in JavaScript I get:

const readonlyProvider = new web3_1.default.providers.HttpProvider(providerURL);

And I see that web3_1.default is undefined in the console.

Answer ā„–1

Back in the early days of web3, the concept of Web3.providers didn't exist. Instead, we had to manually create a provider and then inject it into the new Web3 instance as follows:

let web3;
if (typeof window !== "undefined" && typeof window.web3 !== "undefined") {
  window.ethereum.enable();
  // When using a browser with MetaMask
  // Note: window.web3 is now deprecated, use window.ethereum instead
  web3 = new Web3(window.web3);
} else {
  // For server-side applications or when MetaMask is not available
  const provider = new HDWalletProvider({
    mnemonic: {
      phrase: process.env.METAMASK_KEY,
    },
    providerOrUrl: process.env.YOUR_PRIVATE_NODE, // Possibly GOERLI network
  });

  // This was the method for initializing a Web3 instance back then
  web3 = new Web3(provider);

Answer ā„–2

When you're using the ES6 import syntax to bring in the web3 module, there's a hiccup once the typescript code gets compiled to javascript. The compilation results in a different syntax being used to import the web3 module, leading to the error of web3_1.default being undefined in the console.

If this issue is plaguing you, here are my suggestions:

  1. Switch to using the require syntax instead of import.
const Web3 = require('web3');
const readonlyProvider = new Web3.providers.HttpProvider(providerURL);
  1. Turn on the esModuleInterop setting in your typescript configuration. This option alters how typescript manages imports, potentially resolving your problem.
{
 "compilerOptions": {
   "esModuleInterop": true
 }
}
  1. Try out the import * as syntax. By importing all exports from the web3 module as object properties, typescript may handle things differently.
import * as Web3 from 'web3';
const readonlyProvider = new Web3.providers.HttpProvider(providerURL);

If these suggestions don't work for you or seem unhelpful, please let me know so I can remove them.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Access to property 'foo' is restricted to an instance of the 'Foo' class and can only be accessed within instances of 'Foo'

In my Typescript code, I encountered an error with the line child._moveDeltaX(delta). The error message reads: ERROR: Property '_moveDeltaX' is protected and only accesible through an instance of class 'Container' INFO: (me ...

Simulating NestJS Injected Connection Imported from Another Module

Today, I've been facing this persistent error: Encountering an issue with the ClubsService where Nest is unable to resolve dependencies (specifically DatabaseConnection). The error message prompts me to ensure that the argument DatabaseConnection at i ...

Tips for preventing duplicate imports in Sass with the @use rule in Webpack

My sass modules have the ability to import each other as shown in the examples below: // LinearLayout.scss @mixin LinearLayout { ... } linear-layout { @include LinearLayout; } // ScrollView.scss @use "LinearLayout" as *; @mixin ScrollView { ...

There seems to be a mismatch in compatibility between the register() function in react-hook-form and the native input types

Currently, I'm in the midst of a React project that utilizes TypeScript along with react-hook-form. At one point in my code, I am making use of the provided function register(), which should be implemented as follows according to the official document ...

Defining the signature of an unnamed function in TypeScript

Within my Express code, I have an anonymous function set up like this: app.use((err, req, res, next) => { // ... }); I am looking to specify the type of the function as ErrorRequestHandler (not the return type). One way to achieve this is by defining ...

Prevent clicking outside the bootstrap modal in Angular 4 from closing the modal

Just starting out with angular4 and incorporating bootstrap modal into my project. I want the modal to close when clicking outside of it. Here's the code snippet: //in html <div bsModal #noticeModal="bs-modal" class="modal fade" tabindex="-1" rol ...

What is the best way to integrate a solidity smart contract with a mobile application?

As a beginner in smart contract development, I am eager to build a mobile app that interacts with solidity. However, I am facing uncertainty on how to accomplish this task. While there is extensive documentation available on connecting to web applications ...

Utilizing global enumerations within VueJS

Is there a way to effectively utilize global enums in Vue or declare them differently? My current setup is as follows: Within my types/auth.d.ts: export {}; declare global { enum MyEnum { some = "some", body = "body", o ...

Instantiate a fresh object using the new keyword followed by the Class constructor, and if desired,

I'm looking for a class that I can easily create new instances from and optionally assign properties using the constructor. For instance: class Person { name: string; age: number; constructor(props: {name?: string, age?: number}) { this.nam ...

Saving a picture to your Ionic device

I am currently using the code snippet below to access the device's Photo Library. However, it is returning a base64 encoded string, which has left me feeling unsure of how to proceed with this information. My goal is to save the photo to the applicati ...

Creating a .d.ts file for a JavaScript file that exports a plain object - tips and best practices

I am attempting to include a .d.ts file for an existing js file. The type.js file looks like this: // type.js export default { NORMAL: '001', CHECK: '002', }; Now, I have added a type.d.ts file as follows: // type.d.ts decla ...

Issues with my transpiled and typed TypeScript npm module: How can I effectively use it in a TypeScript project?

I'm trying to experiment with TypeScript. Recently, I created a simple "hello world" TypeScript module and shared it on npm. It's very basic, just has a default export: export default function hello(target: string = 'World'): void { ...

How can I effectively test the success of a form submission in next.js using jest for unit testing?

At the moment, I am in the process of developing a unit test for a registration form within my application. The main objective of this test is to ensure that the registration process can be executed successfully without actually saving any new data into th ...

Obtaining the TemplateRef from any HTML Element in Angular 2

I am in need of dynamically loading a component into an HTML element that could be located anywhere inside the app component. My approach involves utilizing the TemplateRef as a parameter for the ViewContainerRef.createEmbeddedView(templateRef) method to ...

The absence of Index.ts in the TypeScript compilation cannot be resolved by simply including it

Upon integrating @fireflysemantics/slice into my Angular project, I encountered the following error: ERROR in ./node_modules/@fireflysemantics/slice/index.ts Module build failed (from ./node_modules/@ngtools/webpack/src/index.js): Error: /home/ole/Temp/fs ...

Update my SPFx web component to link to a CSS file instead of embedding the CSS styles directly within the component

I recently developed a web part that is reminiscent of a similar one found on GitHub @ https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-enhanced-list-formatting. This particular web part enables the embedding of custom CSS code directly in ...

Working with Typescript: Defining the return type of a function that extracts a subset of an object

Currently, I am attempting to create a function that will return a subset of an object's properties. However, Iā€™m facing some issues with my code and I can't pinpoint the problem. const initialState = { count: 0, mounted: false, } type St ...

Compiler is unable to comprehend the conditional return type

I've done some searching, but unfortunately haven't been able to find a definitive solution to my issue. Apologies if this has already been asked before, I would appreciate any guidance you can offer. The problem I'm facing involves a store ...

What is the best way to assign a value to a class variable within a method by referencing the 'this' keyword?

Is there a way to set the state of this Ionic react app when displaying the outcome of a reset service? I am facing challenges with using this.setState({resetSuccess}) within a method due to scope issues. (Details provided in comments) Here is the relevan ...

Unit testing TypeScript code by creating a mock of the third-party library, ioredis

Struggling to mock a third party library in typescript tests is proving to be quite a challenge. Currently, I am developing a library based on the foundation of the typescript-starter library that utilizes ava for testing. Specifically, I am attempting t ...