webpack: `__non_webpack_require__` incompatible with `experiments.outputModule` + `devtool: 'eval-source-map'`

Bug report

What is the current behavior?

When using experiments.outputModule = true in combination with __non_webpack_require__ and devtool: 'eval-source-map' (or any other of the eval-based devtools), then you get Error: Cannot use 'import.meta' outside a module when trying to run the bundled file. This is because import.meta is accessed in the code that is passed as a string to eval, which does not have access to import.meta.

If the current behavior is a bug, please provide the steps to reproduce.

Full minimal sample project: https://stackblitz.com/edit/github-qjzdxl?file=webpack.config.cjs&view=editor

Run npm install && npm run build && npm run start to get the error.

Important files:

  • package.json which specifies type: "module"
  • webpack.config.cjs:
      const path = require('path');
      
      module.exports = {
        entry: './src/index.js',
        devtool: 'eval-source-map',
        output: {
          filename: 'main.js',
          path: path.resolve(__dirname, 'dist'),
        },
        experiments: {
          outputModule: true,
        },
        optimization: {
          minimize: false,
        },
      };
    
  • src/index.js:
      __non_webpack_require__('path');
      console.log('it worked');
    

What is the expected behavior?

Webpack should use a different mechanism to access import.meta when using an eval-based devtool that avoids accessing import.meta inside of strings passed to eval. Running the compiled file should print it worked to the console.

Other relevant information: webpack version: 5.89.0 Node.js version: 18.18.0 Operating System: Linux Additional tools: None

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 1
  • Comments: 16 (9 by maintainers)

Most upvoted comments

Yeah, PR welcome on such things, unfortunately we can’t conver __non_webpack_require__ to import, because the first is sync, the second is async, actually it is technically possible, but I am not sure we should really implement it in nowadays

@suguanYang __non_webpack_require__ is a Node.js stuff, so webpack generates createRequire, we should generate a warning in such case, but it should not be used for ES modules or by web libraries. Can you provide where do you have it? I see, it’s just a deprecated library that used by our legacy system. And have a warning on such case would be helpful, gonna have a look on it if I have time