I've got a Symfony project with Webpack Encore. MySQL, PHP, Mercure, Yarn/NodeJS, etc. are installed on my machine. Environment variables are accessible by my front-end code.
Relevant code snippets:
# .env.local
MERCURE_HUB_URL=https://localhost/.well-known/mercure
# webpack.config.js
Encore.configureDefinePlugin(options => {
const environment = dotenv.config({
path: './.env.local',
debug: false
})
console.info(environment.parsed)
options['process.env.MERCURE_HUB_URL'] = JSON.stringify(environment.parsed.MERCURE_HUB_URL)
}
# api.js
const hub = new URL(process.env.MERCURE_HUB_URL)
This works great, but now I'm running Node in a container because I'm switching towards using dunglas/symfony-docker. In the new setup my environment variables aren't working as expected. Here's my node container with webpack's dev-server running:
# compose.yaml
encore:
image: node:latest-alpine
volumes:
- .:/app
ports:
- "8080:8080"
working_dir: /app
depends_on:
- php
command: >
sh -c "yarn install && yarn encore dev-server"
While this works (dev-server runs webpack compiles), process
in api.js
is not defined:
api.js:123 Uncaught ReferenceError: process is not defined
The console.info(environment.parsed)
in my webpack.config.js
returns the variables as expected during building, so I don't understand what's going wrong. Any ideas?
Process is not available in the current scope, you could try globally setting the MERCURE var, thus not needing process in "frontend" code. Like this:
.configureDefinePlugin(options => {
const environment = dotenv.config({
path: './.env.local',
debug: false
}).parsed;
options['MERCURE_HUB_URL'] = JSON.stringify(environment.MERCURE_HUB_URL);
You could then use it in api.js like this:
const hub = new URL(MERCURE_HUB_URL);