What is Ethers.js?

Ethers.js is a powerful JavaScript library that allows developers to interact with the Ethereum blockchain and its ecosystem. It provides a simple and intuitive interface for tasks such as sending transactions, interacting with smart contracts, and managing wallets.

Importing Ethers.js

Depending on how you installed Ethers.js, there are different methods to import it into your JavaScript project. Below are the most common methods:

1. Importing Ethers.js in Node.js

If you have installed Ethers.js using npm or Yarn in a Node.js environment, you can import it using the require statement or ES6 import syntax.

Using CommonJS (Node.js)


// Importing Ethers.js using CommonJS
const { ethers } = require('ethers');

// Example: Create a provider
const provider = ethers.getDefaultProvider('homestead');
console.log(provider);

Using ES6 Modules


// Importing Ethers.js using ES6 module syntax
import { ethers } from 'ethers';

// Example: Create a provider
const provider = ethers.getDefaultProvider('homestead');
console.log(provider);

2. Importing Ethers.js in a Browser Environment

If you are building a simple web application and prefer to include Ethers.js directly in your HTML file, you can use a CDN (Content Delivery Network). Here’s how to do it:

<script src="https://cdn.jsdelivr.net/npm/ethers@5.7.0/dist/ethers.umd.min.js"></script>

After including the script in your HTML, Ethers.js will be available globally as the ethers object.

Example HTML Code


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ethers.js Example</title>
<script src="https://cdn.jsdelivr.net/npm/ethers@5.7.0/dist/ethers.umd.min.js"></script>
</head>
<body>
<h1>Ethers.js Example</h1>
<script>
// Using Ethers.js in the browser
const provider = ethers.getDefaultProvider('homestead');
console.log(provider);
</script>
</body>
</html>

Conclusion

Importing Ethers.js into your JavaScript project is straightforward, whether you are using Node.js or a browser environment. Once imported, you can leverage its powerful features to interact with the Ethereum blockchain and build decentralized applications.