Truffle has this whole build process for deploying fronted code that is kinda mediocre. Does anyone know if I can just have Truffle output a single javascript file that will work in a web3 enabled browser and then import that in a much cleaner frontend framework like React?

I guess what is the best way to get all the benefits of Truffle with the secret sauce of React going?


What your app needs from truffle is the truffle-contracts module, plus json contract definitions that truffle builds when you run truffle migrate.

truffle-contracts is a normal NPM library, so you can manage it like any other dependency and load it with something like

const contract = require('truffle-contracts');

The JSON files will change every time you redeploy your contracts, so it's easiest if you can refer directly to them in the place where your truffle install keeps them. A simple way to do it is just to keep the truffle directory inside the main app directory, then load them with something like

const mycontract_json = require('../truffle/build/contracts/MyContract.json'); 

Now you can create contract objects that you can use just like you would in the default truffle build process:

var MyContract = contract(mycontract_json);
MyContract.deployed().then(function(instance) {
    // Interact with your contract as in the Truffle examples

Your truffle.js file can be stripped of everything except the network definitions, as suggested in the webpack example linked by @Ismael. The build section is no longer needed, as all that Truffle is going to be building is the contract definition files.

See this project for a working example. The code above is based on the code used here.

If you're a perfectionist about seamless build processes you might want to create a task in your main project's package.json or whatever it uses that will jump into the truffle directory and run truffle migrate --reset for you, but we didn't bother, and we've never found ourselves wishing we had.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.