Webpack plugin: how to read files of plugin consumer at build time?

Viewed 375

Is it possible to read the contents of the repo which installed my Webpack plugin?

Essentially, I've written a particular JS library which requires the caller to use require.context in their application code to read some files at build time and pass them to the library:

import Library from 'library';

new Library({
  requires: require.context('./foo', false, /\w+\.js$/),
});

I would like to take the burden off of the user and just make that require.context call inside the library to simplify the API to this:

import Library from 'library';

new Library();

However, it doesn't work because the library has no knowledge of when the application code's Webpack build ran.

I've tried writing a Webpack plugin inside the library:

const path = require('path');

class TestPlugin {
  apply(compiler) {
    compiler.hooks.beforeRun.tap('TestPlugin', () => {
      console.log(
        `Path where webpack was executed: ${compiler.options.context}`
      );
    });
  }
}

module.exports = {
  ...
  plugins: [new TestPlugin()],
};

However, this only gets called when the library itself is built not when the application is built.

How can I move the require.context call into the library (which is an NPM dependency) and still have it read the caller's files?

0 Answers
Related