2

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?

Maros
  • 1,825
  • 4
  • 25
  • 56
  • 1
    Just to be clear about what's being asked, you'd like for your npm library to run a plugin during the build of the application it's required in right? – Randy Sep 16 '20 at 02:35
  • Yes that's correct. At a higher level, I want the npm library to require some JS files from the application it's required in *at either build or run time*. Using a webpack plugin is one attempt I tried - open to anything that will work. – Maros Sep 16 '20 at 03:17
  • Is the directory name a variable? If not, maybe you could use a file-loader for a hard-coded path, and then use a require in the library somewhere, I think it would work at compile time too with the rest of the webpack config: https://webpack.js.org/loaders/file-loader/ – A13X Sep 22 '20 at 23:54
  • EDIT: Actually this answer might be more what you are after with requiring it in a library that may already be compiled: https://stackoverflow.com/questions/30575060/require-js-files-dynamically-on-runtime-using-webpack – A13X Sep 22 '20 at 23:59

0 Answers0