You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何在VS Code中搭建React、Truffle、Solidity基础环境

搭建React + Truffle + Solidity 基础环境指南

一、前置依赖安装

  • 安装Node.js(LTS版本),验证安装成功:
    node -v
    npm -v
    
  • 安装Ganache(本地以太坊测试链,可选但推荐):
    桌面版直接官网下载,或命令行安装:
    npm install -g ganache-cli
    
    启动测试链:
    ganache-cli
    

二、配置Truffle环境

  • 全局安装Truffle:
    npm install -g truffle
    
    验证版本:
    truffle version
    
  • 初始化Truffle项目:
    新建项目文件夹(如react-dapp),进入后执行:
    truffle init
    
    生成contracts(合约目录)、migrations(部署脚本)、test(测试目录)、truffle-config.js(配置文件)。
  • 修改truffle-config.js网络配置:
    找到networks字段,添加本地测试链配置:
    networks: {
      development: {
        host: "127.0.0.1",
        port: 8545, // Ganache默认端口
        network_id: "*" // 匹配任意网络ID
      }
    }
    

三、VS Code Solidity开发配置

  • 安装Solidity插件:在VS Code扩展市场搜索Solidity(Juan Blanco开发的官方推荐插件)。
  • 匹配编译器版本:
    打开VS Code设置(Ctrl+,),搜索Solidity: Compile Using Remote Version,设置为与合约pragma声明一致的版本(如0.8.20),确保和Truffle使用的编译器兼容。

四、React项目与Truffle整合

  • 在项目根目录创建React应用:
    npx create-react-app client
    
  • 安装以太坊交互库:
    进入client目录,安装ethers.js(比web3.js更简洁):
    cd client
    npm install ethers
    
  • 编写并部署智能合约:
    1. 在contracts目录新建HelloWorld.sol:
      // SPDX-License-Identifier: MIT
      pragma solidity ^0.8.20;
      
      contract HelloWorld {
        string public message;
      
        constructor() {
          message = "Hello, Dapp!";
        }
      
        function setMessage(string memory newMessage) public {
          message = newMessage;
        }
      }
      
    2. 在migrations目录新建2_deploy_contracts.js部署脚本:
      const HelloWorld = artifacts.require("HelloWorld");
      
      module.exports = function (deployer) {
        deployer.deploy(HelloWorld);
      };
      
    3. 部署合约到本地链:
      回到项目根目录,执行:
      truffle migrate --network development
      
      成功后会在build/contracts生成合约ABI和地址文件。
  • 连接React与合约:
    1. 将根目录build/contracts文件夹复制到client/src目录下。
    2. 修改client/src/App.js:
      import { useEffect, useState } from 'react';
      import { ethers } from 'ethers';
      import HelloWorldABI from './build/contracts/HelloWorld.json';
      
      function App() {
        const [message, setMessage] = useState('');
        const [newMessage, setNewMessage] = useState('');
        const [contract, setContract] = useState(null);
      
        useEffect(() => {
          async function initContract() {
            // 连接MetaMask钱包
            const provider = new ethers.BrowserProvider(window.ethereum);
            const signer = await provider.getSigner();
            // 获取合约地址(Ganache网络ID为5777)
            const contractAddr = HelloWorldABI.networks['5777'].address;
            // 初始化合约实例
            const helloWorld = new ethers.Contract(contractAddr, HelloWorldABI.abi, signer);
            setContract(helloWorld);
            // 获取初始消息
            const currentMsg = await helloWorld.message();
            setMessage(currentMsg);
          }
          initContract();
        }, []);
      
        const updateMsg = async () => {
          if (!contract || !newMessage) return;
          // 发送交易更新消息
          const tx = await contract.setMessage(newMessage);
          await tx.wait();
          // 获取更新后的消息
          const updatedMsg = await contract.message();
          setMessage(updatedMsg);
          setNewMessage('');
        };
      
        return (
          <div className="App" style={{ padding: '2rem' }}>
            <h1>{message}</h1>
            <input
              type="text"
              value={newMessage}
              onChange={(e) => setNewMessage(e.target.value)}
              placeholder="输入新消息"
              style={{ padding: '0.5rem', marginRight: '1rem' }}
            />
            <button onClick={updateMsg} style={{ padding: '0.5rem 1rem' }}>更新消息</button>
          </div>
        );
      }
      
      export default App;
      
    3. 配置MetaMask:添加本地网络(RPC地址http://127.0.0.1:8545,链ID5777,货币符号ETH),导入Ganache生成的测试账户。

五、常见问题排查

  • Truffle部署报错:确保Ganache在运行,端口与truffle-config.js一致,Node.js版本≥16。
  • Solidity语法报错:检查合约pragma版本与VS Code插件配置的编译器版本匹配。
  • React无法连接合约:确认MetaMask已切换到本地网络,合约地址正确,ABI文件路径无误。

内容的提问来源于stack exchange,提问作者Rushikesh Kantule

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 00:45:30