shopware6shopware6-app

Javascript plugin and environment variables


I was reading the documentation here https://developer.shopware.com/docs/guides/plugins/plugins/storefront/add-custom-javascript but cannot find a mention on how to make usage of environment variables in a javascript plugin.

Currently I tried to put a .env file at the root of my plugin in custom/apps/MyPlugin/.env and to capture them via process.env but it fallbacks to my default values...

Is there a way to handle a .env file when you run bash bin/build-storefront.sh?

Thanks.


Solution

  • Here's one way to do it...

    First create a custom webpack.config.js at src/Resources/app/storefront/build. Also in that build directory run npm install dotenv, as you will need it to parse your .env file.

    Your webpack.config.js could then look like this:

    const fs = require('fs');
    const dotenv = require(`${__dirname}/node_modules/dotenv/lib/main.js`);
    
    module.exports = () => {
        // given you `.env` is located directly in your plugin root dir
        const contents = fs.readFileSync(`${__dirname}/../../../../../.env`);
        const config = dotenv.parse(contents);
    
        return {
            externals: {
                myPluginEnv: JSON.stringify(config),
            }
        };
    };
    

    Then inside your sources you can import myPluginEnv.

    import * as myPluginEnv from 'myPluginEnv';
    
    /*
     * Example .env content:
     * FOO=1
     * BAR=1
     */
    
    console.log(myPluginEnv);
    // {FOO: '1', BAR: '1'}