Search code examples
typescriptwebpackwebpack-5

using webpack's require.context is unable to return file content


I'm looking into loading a bunch of text files that are in a directory, and using their content in my code. I tried using fs to read the files like this : fs.readdirbut it doesn't work because my app is browser only, without server.

I found that you can use webpack's require.context() to load the files so I used it like this :

const files = require.context('./my-directory', true, /\.txt$/);
files.keys().forEach((key) => {
  const fileContent = files(key);
  // do something with the file content
});

but const fileContent = files(key); is returning the file name and not the file content.

the docs don't seem to have much answers on how to deal with this and I'm stuck. any suggestions?


Solution

  • I got it.

    I was using the loader (raw-loader) incorrectly, and not making the correct call to get the file content. I was doing this in webpack.config:

        {
            test: /\.txt$/i,
            type: 'asset/resource',
            loader: 'raw-loader',
        },
    

    and the correct way was to remove the type and the correct way to get the file content is like this :

    const files = require.context('./my-directory', true, /\.txt$/);
    files.keys().forEach((key) => {
      const file = files(key);
      const fileContent = file.default;
      // do something with the file content
    });
    

    hope this helps someone.