truffle是以太坊目前最流行的一个开发框架,通过truffle我们可以开发基于以太坊的去中心化应用(Dapp)。这篇文章介绍如何安装truffle并运行第一个Dapp程序。
预备环境要求:
node和npm的安装可参考Ubuntu16.4环境下安装Node.js开发环境。
sudo npm install -g truffle@3.2.1
sudo npm install -g ganache-cli
sudo npm install web3
sudo mkdir DappTest
cd DappTest/
truffle init webpack
自动下载项目模板和相关依赖,项目结构如下
在app.js中找到引入web3的代码,修改为如下形式
window.addEventListener('load', function() {
if (typeof web3 !== 'undefined') {
console.warn("Using web3 detected from external source. If you find that your accounts don't appear or you have 0 MetaCoin, ensure you've configured that source properly. If using MetaMask, see the following link. Feel free to delete this warning. :) http://truffleframework.com/tutorials/truffle-and-metamask")
window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); //window.web3 = new Web3(web3.currentProvider);
} else {
console.warn("No web3 detected. Falling back to http://127.0.0.1:9545. You should remove this fallback when you deploy live, as it's inherently insecure. Consider switching to Metamask for development. More info here: http://truffleframework.com/tutorials/truffle-and-metamask");
window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); // http://127.0.0.1:9545
}
ganache-cli
该窗口不要关闭。
另外打开一个terminal
truffle migrate
npm run dev
打开浏览器,访问localhost:8080,出现以下页面
显示拥有10000METACoin,可以发送给其他账户,所有账户地址列表在之前启动ganache-cli的terminal中可以找到
复制其中一个Account到网页上,并输入100MetaCoin,点击Send MetaCoin
可以当前账户的MetaCoin数量减少100。
至此搭建Truffle并部署测试第一个Dapp项目的教程完结。