Loatheb
Loatheb

Reputation: 62

How to ignore compile `require` to `__webpack_require__` in webpack?

I figure out this question because I use webpack to bundle the code with vm module in it.

For example:

const vm = require('vm');
vm.runInNewContext(`
  const querystring = require('querystring');
  console.log(querystring.parse('foo=bar&abc=xyz&abc=123'));
`, {
  console,
  require,
});

this code run in node is well. when I bundle it by [email protected]. It seems like:

nodeVm.runInNewContext("\n 
  const querystring = require('querystring');\n\n  
  console.log(querystring.parse('foo=bar&abc=xyz&abc=123'));\n          ",{
    console: console,
    require: __webpack_require__(296)
});

by [email protected]. It seems like

nodeVm.runInNewContext("\n
  const querystring = require('querystring');\n\n                
  console.log(querystring.parse('foo=bar&abc=xyz&abc=123'));\n          ", {
    console: console,
    require: !(function webpackMissingModule() { var e = new Error("Cannot find module \".\""); e.code = 'MODULE_NOT_FOUND'; throw e; }())
});

because the require changed to __webpack_require__, the querystring module in vm will be notFound.

Is there any ways to make webpack ignore to change the require to __webpack_require__?

Upvotes: 2

Views: 1351

Answers (1)

EuberDeveloper
EuberDeveloper

Reputation: 1048

I am sure that it works if you want to keep a require as it is, not sure if it works also in your case.

There exist the variable __non_webpack_require__ exactly for that, follow the documentation

const a = __non_webpack_require__(myvar);

becomes:

const a = require(myvar);

after being compiled by webpack.

Upvotes: 3

Related Questions