Luca
07/30/2024, 12:35 AMconst 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 eitherLuca
07/30/2024, 5:57 AM/config
endpoint that the static webapp calls immediately in main before loading anything. It’s working nicely:
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,
}