Search code examples
reactjslaraveldockerenvironment-variableslaravel-mix

Environment variables Laravel Mix in Docker


We have a Laravel 8 application with Laravel Mix 6.0.49 and a React frontend. The application runs inside a docker container in production and development. Up until now, the frontend was compiled outside the docker container for some reason, but since we are moving to a fully dockerized environment, we are required to call the frontend scripts from inside the container. This all works fine, except for an environment variable we are setting in package.json, which allows us to pass the version of the app as a mix variable. Here is the current setup:

// package.json
"version": "0.1.1",
"scripts": {     
  ...
  "watch": "cross-env APP_VERSION=$(node -pe 'require(\"./package.json\").version') mix watch",
  ...

// .env
...
MIX_APP_VERSION="${APP_VERSION}"
...

// MyComponent.jsx
...
<div>version {process.env.MIX_APP_VERSION}</div>
...

The environment variable worked fine when the watch script was called outside the docker container.

Has anyone any idea of why it suddenly does not work anymore? I'm open to other ways of approaching this too.


Solution

  • I fixed this issue in the end by removing the variable related stuff from package.json including the cross-env dependency and setting the environment variable through the webpack config instead (webpack.mix.js)

    ...
    .webpackConfig({
      plugins: [
        new webpack.DefinePlugin({
          'process.env.APP_VERSION': JSON.stringify(
             process.env.npm_package_version,
          ),
        }),
      ],
    })