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
Update your compoents to render the 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:
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.
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: