Is it possible to load a non-existent file?

My use-case is that I need to load a type of file which does not exist but can be generated on-the-fly.

Imagine a file giving the current directory listing and I’d like to import that as ./some/path/dir.json. Obviously I don’t want to create those files in every directory and to maintain them so I wrote a loader to provide the content of the file when it is needed. The problem is that the loader will not be invoked because webpack tries to read the file itself from the system and not finding it breaks the entire chain. I even went on with NormalModuleReplacementPlugin to direct webpack to a file that exists hoping that it will be happy if it loads something but it turned that it actually replaced all references with just one – that dummy file.

Somewhere I read that pitching loaders are able to short-circuit the processing chain when the file content does not matter (as is my case) and tried that but still webpack insists on having a real file or it will not bother to run any loader.

I wonder if there are other options left to get webpack to load such a “virtual” file by passing the import request through my generator and to accept the output of the generator as the content which to be further processed as usual? I may need babel or some CSS stuff run on that content just like one would do with a normal file written to the file system.


Author: Fantashit

2 thoughts on “Is it possible to load a non-existent file?

  1. You can load “non-files” by using a require statement that specifies the loader as such:


    or as an entry point:

    entry: 'mything-loader!',

    then write mything-loader to do whatever you need it to and return whatever code you want.

  2. Oh, I see – to call require() but only specify a loader and no file – didn’t expect that but will give it a try. Thanks

    Ok, it worked even if that made the resources not cacheable but at least I could keep the ES6 import style like

    import thing from 'mything-loader!?some/path';

    The loader then can read ?some/path from this.resourceQuery and know exactly what to produce for this request.


Comments are closed.