marcandrewb
7/2/2019 - 8:53 PM

Injecting JavaScript environment variables at runtime

Injecting JavaScript environment variables at runtime

<html>
<body>
  <script type="text/javascript" src="/env.js"></script>
  <script type="text/javascript" src="/app.js"></script>
</body>
</html>
const express = require('express')
const path = require('path')
const fs = require('fs')
const port = process.env.PORT || 8080
const app = express()

fs.writeFileSync(
  `${__dirname}/config/env.js`,
  `var config = ${process.env.CLIENT_ENV};`
)

app.use(express.static(__dirname + '/dist'))
app.use(express.static(__dirname + '/config'))
app.get('*', function(request, response) {
  response.sendFile(path.resolve(__dirname, 'index.html'))
})

app.listen(port)