Hi guys, I am trying to pack some env vars into a...
# javascript
l
Hi guys, I am trying to pack some env vars into a json file with webpack. I made a simplified version with some hardcoded object;
Copy code
const webpack = require('webpack');

class GenerateEnvJsonPlugin {
    apply(compiler) {
        compiler.hooks.compilation.tap('GenerateEnvJsonPlugin', (compilation) => {
            compilation.hooks.processAssets.tap(
                {
                    name: 'GenerateEnvJsonPlugin',
                    stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
                },
                (assets) => {
                    const envConfig = {
                        NODE_ENV: "test1",
                        API_URL: "test2"
                    };
                    console.log('envConfig', envConfig);
                    const jsonConfig = JSON.stringify(envConfig, null, 2);
                    const filename = 'config.json';

                    // Add the file to the compilation assets so that it is served by webpack-dev-server
                    compilation.emitAsset(filename, new compiler.webpack.sources.RawSource(jsonConfig));
                }
            );
        });
    }
}

config.plugins.push(new GenerateEnvJsonPlugin());
But this does nothing. I have the file in
webpack.config.d/generate-env-json.config.js
any ideas how I can do this? Or even how I can debug it? I can’t get console.log to work in there either
I ended up loading the env variables in a middleware
/config
endpoint that the static webapp calls immediately in main before loading anything. It’s working nicely:
Copy code
const path = require('path');
const dotenv = require('dotenv');

// Construct the path to the .env file located in the repository root
const envPath = path.join(__dirname, '../../../../.env');

// Load environment variables from the .env file
dotenv.config({path: envPath});

config.devServer = {
    ...config.devServer, // merges any locally defined server options
    //<https://webpack.js.org/configuration/dev-server/#devserverhttps>
    allowedHosts: "all",
    port: process.env.PORT ?? 8080,
    // <https://stackoverflow.com/questions/68950266/webpack-dev-server-4-with-ngrok>
    client: {
        webSocketURL: '<auto://0.0.0.0:0/ws>'
    },
    setupMiddlewares: (middlewares, devServer) => {
        if (!devServer) {
            throw new Error('webpack-dev-server is not defined');
        }

        // Add custom middleware to handle /config endpoint
        devServer.app.use('/config', (req, res) => {
            // res.status(500).send(process.cwd());
            const apiUrl = process.env.API_URL;
            const botName = process.env.BOT_NAME;
            res.json({
                apiUrl: apiUrl,
                botName: botName
            });
        });

        return middlewares;
    },
    historyApiFallback: true,
}