6

In general, I want to know how to do code-generation/fabrication in a Webpack plugin on demand. I want to generate contents for files that do not exist when they are "required."

Specifically, I want a plugin that, when I require a directory, automatically requires all files in that directory (recursively).

For example, suppose we have the directory structure:

  • foo
    • bar.js
    • baz.js
  • main.js

And main.js has:

var foo = require("./foo");
// ...

I want webpack to automatically generate foo/index.js:

module.exports = {
  bar: require("./bar"),
  baz: require("./baz")
};

I've read most of the webpack docs. github.com/webpack/docs/wiki/How-to-write-a-plugin has an example of generating assets. However, I can't find an example of how to generate an asset on demand. It seems this should be a Resolver, but resolvers seem to only output file paths, not file contents.

1 Answers1

1

Actually for your use case:

Specifically, I want a plugin that, when I require a directory, automatically requires all files in that directory (recursively).

you don't need a plugin. See How to load all files in a subdirectories using webpack without require statements

Doing code-generation/fabrication on demand can be done in JavaScript quite easily, why would you restrict your code generation specifically to only applied, when "required" by WebPack?

As NodeJS itself will look for an index.js, if you require a directory, you can quite easily generate arbitrary exports:

//index.js generating dynamic exports
var time = new Date();

var dynamicExport = {
  staticFn : function() {
    console.log('Time is:', time);
  }
}

//dynamically create a function as a property in dynamicExport
//here you could add some file processing logic that is requiring stuff on demand and export it accordingly
dynamicExport['dyn' + time.getDay()] = function() {
  console.log('Take this Java!');
}

module.exports = dynamicExport;
Community
  • 1
  • 1
Christian Ulbrich
  • 3,212
  • 1
  • 23
  • 17
  • 1
    I wasn't aware of webpack's `require.context`. Thanks! However, that doesn't solve my problem. I have literally hundreds, probably thousands of code-points where I require a directory and I need to run custom code to scan the files in that directory and decide what to actually load - essentially an index.js file generated on demand. Right now I have a tool which generates these index.js files and writes them to disk. However, this leaves my file-tree littered with machine-generated index.js files. It would be – Shane Brinkman-Davis Jul 24 '18 at 17:12
  • @ShaneBrinkman-Davis Well, then either _monkey-patch_ `require()` or replace the calls to `require` with your own `dynamicGeneratingRequire()` where you need this special behavior if you are using pure NodeJs. For Webpack you would write a custom [Resolver](https://webpack.js.org/api/resolvers/) – Christian Ulbrich Sep 10 '18 at 21:21