Use .env in local plugin

This worked for me with Strapi V4:

  • Rename ./src/admin/webpack.config.example.js to ./src/admin/webpack.config.js.
  • Add the webpack.EnvironmentPlugin, which reads from the current process.env and assigns then to frontend, my full file is below.
"use strict";

/* eslint-disable no-unused-vars */
module.exports = (config, webpack) => {
  // Note: we provide webpack above so you should not `require` it
  // Perform customizations to webpack config

  config.plugins.push(
    new webpack.EnvironmentPlugin(["NODE_ENV", "TEST_VAR"])
  );

  // Important: return the modified config
  return config;
};

From my react code, I can access the variables from the same path from my .env file.

console.log("process.env.NODE_ENV", process.env.NODE_ENV);
console.log("process.env.TEST_VAR", process.env.TEST_VAR);

As a note, I had to manually restart strapi develop --watch-admin each time to see the changes.

6 Likes