How to fix your Truffle and Solidity version errors with NPX (from npm)

Struggling with different versions of your global and local node packages? npm has a brilliant way to solve all your worries!

“Error: ‘module’ is undefined” is a normal bug to encounter when cloning repositories with old truffle versions, where the Truffle configuration file used to be a javascript file called truffle.js.

When developing, testing and migrating smart contract with the Truffle Framework, it is common to stumble upon versioning problems with Truffle.

Given that your coding predecessor has done his job correctly setting up the node package configuration file (package.json) you will find it easy to overcome versioning problems with Truffle and Solidity.

If you followed the steps on Truffle’s documentation site, you probably executed a global installation of your truffle package.

A better way to do it, is simply not to do it!

How then, you ask? 
Use npx! (which you probably already have)

An example flow could be as follows:

Step 1. You clone a repository using Git

git clone https://some-old-truffle-repository.com

Step 2. You change to this directory

cd some-old-truffle-repository

Step 3. You install the node packages

npm install

Step 4. You try to compile, test and migrate contracts with your global installation of Truffle

truffle compile
truffle test
truffle migrate

But… errors!

“Source file requires different compiler version (current compiler is 0.5.0+commit.1d4f565a.Emscripten.clang — note that nightly builds are considered to be strictly less than the released version)” is a common problem to encounter.

FIX: A more reliable way to using Truffle!

Swap your Step 4: Compile, test, and migrate using your local Truffle version!

npx truffle compile
npx truffle test
npx truffle migrate

What’s going on here?

npx is a native npm package, so it comes with your installation of nodejs & npm.

It allows you to run local node package binaries. This way, you can get rid of a lot of your global package installations, and use the local binaries that are defined in your package.json.

Kat Marchán has already written an awesome guide to using npx, check it out!

For your own and others’ sake, remember to always have correct versioning in your package.json in the future!

Cheers!

Anything else on Ethereum development you want to hear about? Hit me up!