privatenumber / esbuild-loader

💠 Speed up your Webpack with esbuild ⚡️
MIT License
3.58k stars 106 forks source link

"Module not found" error causes esbuild-loader to crash with "Cannot read properties of undefined (reading 'useSourceMap')" #356

Closed panta82 closed 9 months ago

panta82 commented 9 months ago

Problem

When there is a problem with module resolution during build, webpack emits "finishModules" event with an empty set.

esbuild-loader responds to this event by trying to extract useSourceMap. Since it is given an empty set, it crashes on this line: https://github.com/privatenumber/esbuild-loader/blob/develop/src/plugin.ts#L212

Suggested fix:

    compilation.hooks.finishModules.tap(
      pluginName,
      (modules) => {
        const firstModule = Array.isArray(modules) ? modules[0] : modules.values().next().value;
        if (firstModule) {
          useSourceMap = firstModule.useSourceMap;
        }
      }
    );

Expected behavior

Webpack is able to finish and report the actual error.

Minimal reproduction URL

https://stackblitz.com/edit/node-t2tcae?file=webpack.config.js,package.json&view=editor

Version

4.0.2

Node.js version

16.20.0

Package manager

npm

Operating system

Linux

Contributions

privatenumber commented 9 months ago

Nice catch!

Would you mind opening a PR with fix + test?

panta82 commented 9 months ago

I wouldn't mind. I mostly didn't because I don't have this project set up, and testing this seems like it would be tricky. Let me check it out, and I'll let you know if I can handle it.

panta82 commented 9 months ago

Figured it out, I think.