2

in requirejs there is a way to configure modules configure modules, so the configuration is available in the module using module.config(). what's webpack's alternative?

zowers
  • 587
  • 6
  • 13

1 Answers1

0

Webpack doesn't provide any specific mechanism for this. We can build one on top of it, though. Webpack allows us to get current __filename. As discussed in that answer, after doing

module.exports = {
  context: __dirname,
  node: {
    __filename: true
  }
}

Accessing __filename at a module will give us path to it.

We can combine this idea with resolve.alias. Example configuration:

{
  resolve: {
    alias: {
      config: path.join(__dirname, './config')
    }
  }
}

After this we can do

var config = require('config')(__filename);

and you can return the module specific configuration you want from your configuration module.

Juho Vepsäläinen
  • 26,573
  • 12
  • 79
  • 105
  • resolve.alias is not module-specific as I understand – zowers Sep 29 '15 at 14:58
  • I'm not sure I get the point. You can use it to point at some directory to perform lookups below it or alternatively you can point to an individual file in which case it would map that directly instead. – Juho Vepsäläinen Sep 29 '15 at 15:01
  • the point is that in requirejs you can configure each module with it's own configuration, which is later available in the module by calling `module.config()` – zowers Sep 30 '15 at 06:12
  • @zowers Got it. We can do something similar through modules. I'll expand my answer with the basic idea. – Juho Vepsäläinen Sep 30 '15 at 07:37
  • @zowers I added a proposed solution. It's probably not as nice as the one you get through requirejs but it should work. – Juho Vepsäläinen Sep 30 '15 at 07:47
  • this somehow emulates requirejs' config but is not as easy to understand and use. also it does not allow sending dynamic configuration. probably the main answer to the question is as you put it: "Webpack doesn't provide any specific mechanism for this". – zowers Sep 30 '15 at 10:21
  • Yeah. It might be possible to [implement a plugin](https://webpack.github.io/docs/plugins.html) that gets closer to what you want. I would start by figuring out what [ProvidePlugin](https://github.com/webpack/webpack/blob/master/lib/ProvidePlugin.js) does and then move from there. This way you could for example give a global `config` object that maps to configuration associated with the file. – Juho Vepsäläinen Sep 30 '15 at 11:02