0

I'm trying to follow the guide to Writing a Loader using Webpack 5.2.0. At the bottom of the page we are guided through a simple Jest test sample. The Jest test checks that the first module object source property is the source that our loader generated. I can verify that my Webpack compiler step generated a module with a name property of ./example.txt. But the source property is always 'undefined'. This is despite stats.hasErrors() returning false.

I'm new to Webpack loader development and I'm not sure what I'm missing. The module structure description indicates this property should contain my module source if it was successful.

Have others successfully completed this scenario with a recent verison of Webpack?

pglezen
  • 961
  • 8
  • 18

2 Answers2

1

After some time of googling i found that for webpack@5 you need to pass additional options to have source field in output.

stats.toJson({
  source: true
});
Lesha Ogonkov
  • 1,218
  • 8
  • 20
0

Just to add some context to this answer, in order to make the Webpack5 Writing a Loader, Testing Section work (as it was 10/31/2020), adjust the following. With Lesha's suggestion above, the output line in test/loader.test.js should read

const output = stats.toJson({source: true}).modules[0].source;

That solves the missing source attribute problem. The Jest test will still fail unless you created the example.txt without a newline on the end. Either ensure there is no line ending or change your expect clause to the following:

expect(output).toBe('export default "Hey Alice!\\n"');
pglezen
  • 961
  • 8
  • 18