Create react app: script tag url depending on environment
We have a React app created with create-react-app.
We have to include an external script tag in the head tag (in the public/index.html
file).
The provider of the script provides us 2 snippets: one for development and one for the production environment.
For example, in development environment, the script tag is :
<script src="https://myscript.org/scripttemplates/script.js" type="text/javascript" charset="UTF-8" data-domain-script="4a1xxxxx-xxx-xxxx-xxxxx-test"></script>
<script type="text/javascript">
function OptanonWrapper() { }
</script>
For production environment, the script tag is:
<script src="https://myscript.org/scripttemplates/script.js" type="text/javascript" charset="UTF-8" data-domain-script="4a1xxxxx-xxx-xxxx-xxxxx"></script>
<script type="text/javascript">
function OptanonWrapper() { }
</script>
So you can see that the only difference is the data-domain-script
attribute between the 2 environments.
So my question is, how can we put the good snippet depending of the environment?
Thanks in advance.
Solution 1:
<script>
const x = env === 'prod' ? prodCDN : otherCDN;
document.write("<script type='text/javascript' src='"+ x + "'><\/scr" + "ipt>");
</script>
Solution 2:
in our application we are using this based on env
variables in our public/index.html
:
<% if (process.env.NODE_ENV === 'production') { %>
<script src="https://myscript.org/scripttemplates/script.js" type="text/javascript" charset="UTF-8" data-domain-script="4a1xxxxx-xxx-xxxx-xxxxx-test"></script>
<% } else { %>
<script src="https://myscript.org/scripttemplates/script.js" type="text/javascript" charset="UTF-8" data-domain-script="4a1xxxxx-xxx-xxxx-xxxxx"></script>
<% } %>
Node.js will generate classic html based on env variable