spence-s / simple-pug-loader

Simpler than pug-loader
https://www.npmjs.com/package/simple-pug-loader
MIT License
14 stars 4 forks source link

Add the file where an error occurred as a dependency #9

Closed b3nsn0w closed 2 years ago

b3nsn0w commented 2 years ago

Ran into this error while using simple-pug-loader: I had two files, index.pug and lib.pug, and when I made a syntax error in lib.pug, fixing the error did not trigger a recompile. Even worse, when I saved an unrelated file in the project, it did trigger a recompile, but it kept the pug error cached, and initially it seemed like if you make an error in a pug file, you'll need to restart the entire webpack server.

After a while, I managed to figure out that if you fix the error in lib.pug, then save index.pug, it does recompile successfully. I'm kinda new to webpack plugin dev, but as far as my current understanding goes, it's because of this snippet:

/*
 * Compile the pug
 */
const compilation = pug.compileClientWithDependenciesTracked(
  source,
  pugOptions
);

func = compilation.body;

/*
 * Let webpack know to watch the dependencies
 */
if (compilation.dependencies && compilation.dependencies.length > 0)
  for (const dep of compilation.dependencies)
    loaderContext.addDependency(dep);

This is in a try-catch block, expecting an error on pug.compileClientWithDependenciesTracked(), and returning it to webpack if anything goes sideways. However, the code which tells webpack which dependencies to watch is after that line, and therefore won't get executed if there's a pug error, even if it happened in a dependency.

I've added this line to the catch block:

/*
 * Add the file where the error occurred as a dependency
 */
loaderContext.addDependency(path.normalize(error.filename));

I don't know if there's a way to recover a list of dependencies after an error, but with this one, you at least get the offending one on the list. In this case, if you have index.pug, lib1.pug, and lib2.pug, and you make a mistake in lib2.pug, the code will unfortunately stop watching lib1.pug, but at least if you fix lib2.pug it does catch on and update automatically.

spence-s commented 2 years ago

Great find, thanks for this! I created an issue https://github.com/Spence-S/simple-pug-loader/issues/10 for this and published the patch to npm.

b3nsn0w commented 2 years ago

Awesome! Thanks for the quick merge