4. October 2017

Webpack: How to read version from file and render it into React web

Imagine the simple scenario.The string with version is stored in the file, and it is necessary to transport it from the file into a React application using Webpack.

The solution is relatively simple.

The whole idea is to execute child process which will read the file and transfers the content via variable into the application.

You will need DefinePlugin which allows defining a custom variable and transports it into the transpiler.

Update your package.json and add there

new webpack.DefinePlugin({
   __VERSION__: JSON.stringify('1.2.3')
})

Update your compoents to render the version:

... {__VERSION__} ...

Check the application and you should see there version 1.2.3.

Let’s move further and read a value from the file version.txt. You will need child_process. Add following line to package.json:

const childProcess = require('child_process');

Now update our previous code to read the value from the file. It is necessary to wrap the output into JSON.stringify otherwise you won’t be able to render the version properly.

new webpack.DefinePlugin({
   __VERSION__: JSON.stringify(childProcess.execSync('cat version.txt').toString())
})

This command will invoke the cat command and the output of the command will be set to variable.

If you want a little bit more portable version of the script, then use ShellJS instead of a plain cat.

The code with ShellJS will look like this:

cons shell = require('shelljs');

new webpack.DefinePlugin({
   __VERSION__: JSON.stringify(shell.cat('version.txt').toString())
})