Skip to content
This repository was archived by the owner on Mar 5, 2025. It is now read-only.

Commit d446838

Browse files
danforbesjdevcs
andauthored
Lightweight dApp Development Guide (#7364)
* Lightweight dApp Development Guide Closes #7300 * Fix Broken Discord Link * Apply suggestions from code review Co-authored-by: Junaid <86780488+jdevcs@users.noreply.github.com> --------- Co-authored-by: Junaid <86780488+jdevcs@users.noreply.github.com>
1 parent 4aaf915 commit d446838

File tree

7 files changed

+283
-7
lines changed

7 files changed

+283
-7
lines changed

docs/docs/guides/01_getting_started/introduction.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ sidebar_label: Introduction
88

99
Web3.js is a robust and flexible collection of **TypeScript and JavaScript** libraries that allows developers to interact with local or remote [Ethereum](https://ethereum.org/en/) nodes (or **any EVM-compatible blockchain**) over **HTTP, IPC or WebSocket** connections. It is a powerful and efficient toolkit for crafting applications within the Ethereum ecosystem and beyond.
1010

11-
This documentation is the entrypoint to Web3.js for developers. It covers [basic](/guides/getting_started/quickstart) and [advanced](/guides/smart_contracts/mastering_smart_contracts) usage with examples, and includes comprehensive [API documentation](/api) as well as guides for common tasks, like [upgrading](/guides/web3_upgrade_guide) from older versions.
11+
This documentation is the entrypoint to Web3.js for developers. It covers [basic](/guides/getting_started/quickstart) and [advanced](/guides/dapps/lightweight-dapp) usage with examples, and includes comprehensive [API documentation](/api) as well as guides for common tasks, like [upgrading](/guides/web3_upgrade_guide) from older versions.
1212

1313
## Features of Web3.js v4
1414

@@ -35,7 +35,7 @@ New Web3.js developers should proceed to the [Quickstart](/guides/getting_starte
3535

3636
### For Intermediate & Advanced Web3.js Developers
3737

38-
If you're already familiar with Ethereum and Web3.js development, you may want to review the Web3.js [package structure](#packages--plugins) and proceed directly to the [package-level documentation](/libdocs/ABI) and [API documentation](/api). Application developers may wish to review the [Web3.js configuration guide](/guides/web3_config) or learn how to use Web3.js with tools like the [MetaMask](/guides/dapps/metamask-react) wallet or the [WalletConnect](/guides/dapps/web3_modal_guide) wallet selection modal. Don't forget to review the [list of available plugins](https://web3js.org/plugins) or even [learn how to build your own Web3.js plugin](/guides/web3_plugin_guide/plugin_authors)!
38+
If you're already familiar with Ethereum and Web3.js development, you may want to review the Web3.js [package structure](#packages--plugins) and proceed directly to the [package-level documentation](/libdocs/ABI) and [API documentation](/api). Application developers may wish to review the [Web3.js configuration guide](/guides/web3_config) or learn how to use Web3.js with tools like [EIP-6963 wallets](/guides/dapps/intermediate-dapp) or the [WalletConnect](/guides/dapps/web3_modal_guide) wallet selection modal. Don't forget to review the [list of available plugins](https://web3js.org/plugins) or even [learn how to build your own Web3.js plugin](/guides/web3_plugin_guide/plugin_authors)!
3939

4040
## Packages & Plugins
4141

docs/docs/guides/04_transactions/transactions.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ Here is a high-level overview of the steps we will be taking in this tutorial:
1919
6. Send a raw transaction
2020

2121
:::tip
22-
If you encounter any issues while following this guide or have any questions, don't hesitate to seek assistance. Our friendly community is ready to help you out! Join our [Discord](https://discord.gg/F4NUfaCC) server and head to the **#web3js-general** channel to connect with other developers and get the support you need.
22+
If you encounter any issues while following this guide or have any questions, don't hesitate to seek assistance. Our friendly community is ready to help you out! Join our [Discord](https://discord.gg/pb3U4zE8ca) server and head to the **#web3js-general** channel to connect with other developers and get the support you need.
2323
:::
2424

2525
## Step 1: Prerequisites

docs/docs/guides/05_smart_contracts/smart_contracts_guide.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ Here is a high-level overview of the steps we will be taking in this tutorial:
2020
7. Use Web3.js to interact with the smart contract
2121

2222
:::tip
23-
If you encounter any issues while following this guide or have any questions, don't hesitate to seek assistance. Our friendly community is ready to help you out! Join our [Discord](https://discord.gg/F4NUfaCC) server and head to the **#web3js-general** channel to connect with other developers and get the support you need.
23+
If you encounter any issues while following this guide or have any questions, don't hesitate to seek assistance. Our friendly community is ready to help you out! Join our [Discord](https://discord.gg/pb3U4zE8ca) server and head to the **#web3js-general** channel to connect with other developers and get the support you need.
2424
:::
2525

2626
## Step 1: Prerequisites

docs/docs/guides/07_dapps/intermediate-dapp.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ Here is a high-level overview of the steps in this tutorial:
2525
6. Create a form to transfer ether
2626

2727
:::tip
28-
If you encounter any issues while following this guide or have any questions, don't hesitate to seek assistance. Our friendly community is ready to help you out! Join our [Discord](https://discord.gg/F4NUfaCC) server and head to the **#web3js-general** channel to connect with other developers and get the support you need.
28+
If you encounter any issues while following this guide or have any questions, don't hesitate to seek assistance. Our friendly community is ready to help you out! Join our [Discord](https://discord.gg/pb3U4zE8ca) server and head to the **#web3js-general** channel to connect with other developers and get the support you need.
2929
:::
3030

3131
## Step 1: Prerequisites
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,276 @@
1+
---
2+
sidebar_position: 4
3+
sidebar_label: 'Tutorial: Lightweight dApp Development'
4+
---
5+
6+
# Lightweight dApp Development
7+
8+
In web development, the term "bundle size" refers to the aggregate size of all the files that are delivered to a user when they visit a web page. Large bundle sizes result in long loading times, poor performance, and overall bad user experience. A web application with a relatively small bundle size can be described as "lightweight".
9+
10+
The [modular design](/#packages--plugins) of Web3.js promotes lightweight dApp development by allowing developers to include only the capabilities that are required for their dApp. Furthermore, Web3.js makes use of modern [JavaScript module](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) syntax to facilitate [tree shaking](https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking), which is a powerful mechanism for removing unused code that would otherwise be included in a web application.
11+
12+
This guide will apply lightweight dApp development techniques to the minimal React template provided by the [`create-web3js-dapp` command-line utility](https://github.com/web3/create-web3js-dapp). [Webpack Bundle Analyzer](https://github.com/webpack-contrib/webpack-bundle-analyzer) will be used to analyze the impact of these techniques.
13+
14+
## Overview
15+
16+
Here is a high-level overview of the steps in this tutorial:
17+
18+
1. Review prerequisites
19+
2. Initialize a new Web3.js dApp and add dependencies
20+
3. Configure and analyze a development build
21+
4. Analyze the built-in React production build
22+
5. Use only necessary packages and analyze the result
23+
24+
:::tip
25+
If you encounter any issues while following this guide or have any questions, don't hesitate to seek assistance. Our friendly community is ready to help you out! Join our [Discord](https://discord.gg/pb3U4zE8ca) server and head to the **#web3js-general** channel to connect with other developers and get the support you need.
26+
:::
27+
28+
## Step 1: Prerequisites
29+
30+
This tutorial assumes basic familiarity with the command line as well as familiarity with React and [Node.js](https://nodejs.org/). Before starting this tutorial, ensure that Node.js and its package manager, npm, are installed.
31+
32+
```console
33+
$: node -v
34+
# your version may be different, but it's best to use the current stable version
35+
v20.14.0
36+
$: npm -v
37+
10.8.2
38+
```
39+
40+
## Step 2: Initialize a New Web3.js dApp and Add Dependencies
41+
42+
Use `create-web3js-dapp` to initialize a new Web3.js dApp and navigate into the new project directory:
43+
44+
```console
45+
npm install -g create-web3js-dapp
46+
npx create-web3js-dapp --framework react --template minimal
47+
cd web3js-react-dapp-min
48+
```
49+
50+
Add the dependencies that will be used to generate the development bundle and analyze the bundle size:
51+
52+
```console
53+
npm i -D @babel/core @babel/preset-env \
54+
@babel/preset-react @babel/preset-typescript \
55+
babel-loader html-webpack-plugin webpack \
56+
webpack-bundle-analyzer webpack-cli
57+
```
58+
59+
## Step 3: Configure and Analyze a Development Build
60+
61+
For the purposes of this guide, a baseline development build will be configured to allow comparison with React's built-in production build. This initial development build will not make use of the modular design of Web3.js nor will it make use of tree shaking.
62+
63+
The first step to configuring the development build is to create a template HTML file. Create a new file in the project's root directory called `index.html` and populate it with the following text:
64+
65+
```html
66+
<!DOCTYPE html>
67+
<html lang="en">
68+
<head>
69+
<title>Web3.js Lightweight dApp Development</title>
70+
</head>
71+
<body>
72+
<div id="root"></div>
73+
</body>
74+
</html>
75+
```
76+
77+
Next, create a file called `webpack.config.js` and add the following code:
78+
79+
```js
80+
const path = require('path');
81+
82+
const HtmlWebpackPlugin = require('html-webpack-plugin');
83+
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
84+
85+
module.exports = {
86+
mode: 'development',
87+
entry: path.join(__dirname, 'src', 'index.tsx'),
88+
module: {
89+
rules: [
90+
{
91+
exclude: /node_modules/,
92+
test: /\.(ts|tsx)$/,
93+
use: {
94+
loader: 'babel-loader',
95+
options: {
96+
presets: [
97+
'@babel/preset-env',
98+
['@babel/preset-react', { runtime: 'automatic' }],
99+
'@babel/preset-typescript',
100+
],
101+
},
102+
},
103+
},
104+
],
105+
},
106+
output: {
107+
path: path.join(__dirname, 'dist'),
108+
filename: 'index_bundle.js',
109+
},
110+
resolve: {
111+
extensions: ['.ts', '.tsx'],
112+
},
113+
plugins: [new HtmlWebpackPlugin({ template: 'index.html' }), new BundleAnalyzerPlugin()],
114+
};
115+
```
116+
117+
To generate the development build and display the output of Webpack Bundle Analyzer, execute the following command:
118+
119+
```console
120+
npx webpack
121+
```
122+
123+
This will open a new browser tab that displays the output of Webpack Bundle Analyzer. Although the exact bundle size will vary, at the time of writing this guide, the size of the bundle generated by the development build is about **3.3 megabytes**. After reviewing the output of Webpack Bundle Analyzer, close the browser tab and use `Ctrl + C` to cancel the Webpack process.
124+
125+
## Step 4: Analyze the Built-In React Production Build
126+
127+
Next, write a script to analyze React's built-in production build. Create a file called `analyze.js` and add the following code:
128+
129+
```js
130+
const webpack = require('webpack');
131+
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
132+
133+
process.env.NODE_ENV = 'production';
134+
135+
const config = require('react-scripts/config/webpack.config')('production');
136+
config.plugins.push(new BundleAnalyzerPlugin({ analyzerPort: 8089 }));
137+
138+
webpack(config, (err, stats) => {
139+
if (err || stats.hasErrors()) {
140+
console.error(err);
141+
}
142+
});
143+
```
144+
145+
To generate the built-in production build and display the output of Webpack Bundle Analyzer, execute the following command:
146+
147+
```console
148+
node analyze.js
149+
```
150+
151+
At the time of writing this guide, the size of the bundle generated by the built-in production build is about **593 kilobytes**, which is about 2% the size of the initial development build. The reduction in bundle size is due to techniques such as tree shaking. After reviewing the output of Webpack Bundle Analyzer, close the browser tab and use `Ctrl + C` to cancel the Webpack process.
152+
153+
## Step 5: Use Only Necessary Packages and Analyze the Result
154+
155+
The minimal template dApp that was created by `create-web3js-dapp` uses the umbrella `web3` package, which is useful for development purposes but results in a relatively large bundle size. In fact, the capabilities of the minimal React template only require the `web3-eth` and `web3-types` packages. To replace the umbrella `web3` package with `web3-eth` and `web3-types`, execute the following commands:
156+
157+
```console
158+
npm uninstall web3
159+
npm i web3-eth web3-types
160+
```
161+
162+
Next, update the template dApp to remove references to the umbrella `web3` package and make use of the `web3-eth` and `web3-types` packages. Replace the contents of `src/react-app-env.d.ts` with the following:
163+
164+
```ts
165+
/// <reference types="react-scripts" />
166+
167+
import type { EIP1193Provider, Web3APISpec } from 'web3-types';
168+
169+
declare global {
170+
interface Window {
171+
ethereum?: EIP1193Provider<Web3APISpec>;
172+
}
173+
}
174+
```
175+
176+
Replace the contents of `src/web3/web3-service.ts` with:
177+
178+
```ts
179+
import { Web3Eth } from 'web3-eth';
180+
import type { EIP1193Provider, Web3APISpec } from 'web3-types';
181+
182+
const provider: EIP1193Provider<Web3APISpec> | undefined = window.ethereum;
183+
if (provider !== undefined) {
184+
provider.on('chainChanged', () => window.location.reload());
185+
}
186+
187+
const web3: Web3Eth = provider === undefined ? new Web3Eth() : new Web3Eth(provider);
188+
const Web3Service = { provider, web3 };
189+
190+
export default Web3Service;
191+
```
192+
193+
Finally, replace the contents of `src/App.tsx` with the following (only the highlighted line has changed):
194+
195+
```ts
196+
import { useState } from 'react';
197+
198+
import Web3Service from './web3/web3-service';
199+
200+
function App() {
201+
const hasProvider = Web3Service.provider !== undefined;
202+
const [chainId, setChainId] = useState<bigint>(0n);
203+
if (hasProvider) {
204+
// highlight-next-line
205+
Web3Service.web3.getChainId().then(setChainId);
206+
}
207+
208+
return (
209+
<main>
210+
<h1>Web3.js + React Minimal dApp Template</h1>
211+
<div>
212+
This is a sample project that demonstrates using{' '}
213+
<a href="https://web3js.org/">Web3.js</a> with the{' '}
214+
<a href="https://react.dev/">React</a> front-end framework.
215+
<ul>
216+
<li>
217+
<a href="https://docs.web3js.org/">Web3.js Docs</a>
218+
</li>
219+
<li>
220+
<a href="https://react.dev/learn">React Docs</a>
221+
</li>
222+
</ul>
223+
Learn more about this project and its design by referring to the{' '}
224+
<a href="https://github.com/web3/create-web3js-dapp/blob/main/templates/min/web3js-react-dapp-min/README.md">
225+
GitHub README
226+
</a>
227+
.
228+
</div>
229+
{!hasProvider ? (
230+
<>
231+
<h2>Install a Wallet</h2>
232+
<div>Install a wallet browser extension:</div>
233+
<ul>
234+
<li>
235+
<a href="https://www.enkrypt.com/download.html">Enkrypt</a>
236+
</li>
237+
<li>
238+
<a href="https://www.exodus.com/download/">Exodus</a>
239+
</li>
240+
<li>
241+
<a href="https://metamask.io/download/">MetaMask</a>
242+
</li>
243+
<li>
244+
<a href="https://trustwallet.com/download">Trust Wallet</a>
245+
</li>
246+
</ul>
247+
</>
248+
) : (
249+
<>
250+
<h2>Network Details</h2>
251+
<div>Chain ID: {chainId.toString()}</div>
252+
</>
253+
)}
254+
<br />
255+
<i>
256+
This project was bootstrapped with{' '}
257+
<a href="https://github.com/facebook/create-react-app">Create React App</a>.
258+
</i>
259+
</main>
260+
);
261+
}
262+
263+
export default App;
264+
```
265+
266+
Finally, use the `analyze.js` script to analyze the size of the bundle generated by the updated production build by running the following command:
267+
268+
```console
269+
node analyze.js
270+
```
271+
272+
At the time of writing this guide, the size of the final bundle is **467 kilobytes**, or about 75% the size of the bundle before using only the necessary packages.
273+
274+
## Conclusion
275+
276+
Managing bundle size is one of the most important considerations for web developers. Web3.js is designed to give developers control over bundle size. The modular design of Web3.js facilitates the selective use of only required dependencies. The use of JavaScript modules allows build tools like Webpack to remove unnecessary code through tree shaking. Understanding and deploying these techniques allows Web3.js developers to create dApps that are feature-rich while still being lightweight and performance-preserving.

docs/docs/guides/07_dapps/metamask-react.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ Here is a high-level overview of the steps we will be taking in this tutorial:
2121
6. Verify the account used to sign a message
2222

2323
:::tip
24-
If you encounter any issues while following this guide or have any questions, don't hesitate to seek assistance. Our friendly community is ready to help you out! Join our [Discord](https://discord.gg/F4NUfaCC) server and head to the **#web3js-general** channel to connect with other developers and get the support you need.
24+
If you encounter any issues while following this guide or have any questions, don't hesitate to seek assistance. Our friendly community is ready to help you out! Join our [Discord](https://discord.gg/pb3U4zE8ca) server and head to the **#web3js-general** channel to connect with other developers and get the support you need.
2525
:::
2626

2727
## Step 1: Prerequisites

docs/docs/guides/07_dapps/metamask-vanilla.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ Here is a high-level overview of the steps we will be taking in this tutorial:
1919
6. Verify the account used to sign a message
2020

2121
:::tip
22-
If you encounter any issues while following this guide or have any questions, don't hesitate to seek assistance. Our friendly community is ready to help you out! Join our [Discord](https://discord.gg/F4NUfaCC) server and head to the **#web3js-general** channel to connect with other developers and get the support you need.
22+
If you encounter any issues while following this guide or have any questions, don't hesitate to seek assistance. Our friendly community is ready to help you out! Join our [Discord](https://discord.gg/pb3U4zE8ca) server and head to the **#web3js-general** channel to connect with other developers and get the support you need.
2323
:::
2424

2525
## Step 1: Prerequisites

0 commit comments

Comments
 (0)