0

I'm adding Webpack to a Node/Express app that previously used RequireJS. When the client needed some configuration from the server, we previously used a custom Express route that retrieved specific configs as JSON:

server/index.js - Set up Express routes for config files

const app = express();
const configRouter = express.Router();
configRouter.get('/some-config.json', (req, res) => {
    const someConfig = {
        prop1: getProp1(),
        prop2: getProp2()
    }
    res.json(someConfig);
}
app.use('/config', configRouter);

client/controller.js - Use/config/some-config.json during initialization

define(['text!/config/some-config.json'], function(SomeConfig) {
    // do something with SomeConfig
});

But removing RequireJS means I can no longer retrieve the JSON this way as a dependency. And it's not static JSON either, so it's not as simple as just placing it alongside client code and importing it.

So what is the best way to do this with Webpack? Any help greatly appreciated. Thanks!

Matt
  • 23,363
  • 39
  • 111
  • 152
  • I'm kinda confused. The `some-config.json` resides on the server if I understand, the clients needs to pull it from the API (from what u wrote). So why not just call the api then use the file in the client? What does webpack have to do with this? – HRK44 Mar 20 '19 at 13:30
  • @HRK44 I just wondered if perhaps there was a more efficient way to leverage Webpack to build in those configurations as part of the bundle and then simply hydrate my client application with them and/or import them from my client code. I'd personally prefer that sort of solution over having to immediately make an AJAX call to the server as soon as my application loads in the browser. Hope that clears up the question. – Matt Mar 20 '19 at 13:53
  • it is possible to integrate files into your webpack bundle, but that will be just done once at build time. If, as you state, your file is 'not static' then it kinda defies the purpose, since you bundle static files. – HRK44 Mar 20 '19 at 14:20
  • Well, maybe a liberal use of the phrase "not static". I never expect configuration to change during runtime, and it's safe for it to be bundled with the build and made statically available. My only reason for saying "not static" is because the server uses `nconf` to retrieve values to build the JSON when the endpoint is called (see `getProp1()` and `getProp2()` in my post). But again, there's no reason none of that couldn't be done at build time and then included with the bundle for access by the client somehow. In fact, I'd prefer that. – Matt Mar 20 '19 at 14:31
  • Maybe have a look at https://webpack.js.org/loaders/json-loader/ then – HRK44 Mar 20 '19 at 14:38
  • I'm aware that you can import json files. My question is how to properly provide them to the client for importing. – Matt Mar 20 '19 at 15:05

0 Answers0