Tag Archives: require

Causes and solutions of error reporting in require setting dynamic path

Thrown error:

 Error: Cannot find module 'D:\xxx\resources\set_pac.node'
      at webpackEmptyContext (webpack:///./src/main/modules_sync?:2:10)
      at eval (webpack:///./src/main/modules/proxyConfig.js?:23:70)
      at Module../src/main/modules/proxyConfig.js (D:\xxx\dist\electron\main.js:801:1)
      at __webpack_require__ (D:\xxx\dist\electron\main.js:21:30)
      at eval (webpack:///./src/main/index.js?:6:78)
      at Module../src/main/index.js (D:\xxx\dist\electron\main.js:766:1)
      at __webpack_require__ (D:\xxx\dist\electron\main.js:21:30)
      at eval (webpack:///./src/main/index.dev.js?:11:1)
      at Object../src/main/index.dev.js (D:\xxx\dist\electron\main.js:754:1)
      at __webpack_require__ (D:\xxx\dist\electron\main.js:21:30)

Solution

const setpac_path = path.join(process.cwd(), '/resources/set_pac.node');
log.info('pac_path', setpac_path);

const requireFunc = typeof __webpack_require__ === "function" ?__non_webpack_require__ : require;
const setPac = requireFunc(setpac_path);

https://stackoverflow.com/questions/42797313/webpack-dynamic-module-loader-by-require/53074814#53074814
https://github.com/webpack/webpack/issues/4175#issuecomment-342931035

Error reporting of require occurs during webpack packaging

Error description

Usually, problems often occur in the target: 'node' environment

There is a problem in the compiled file. Use require as follows:

// for example 1:
const reload = require('require-reload')(requireFunc)

// for example 2:
function main () {
    var data = require(dataPath)
}

An error will be reported when packing:

Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
Critical dependency: the request of a dependency is an expression

Error resolution

Add the following code to the compiled file:

const requireFunc = typeof __webpack_require__=== 'function' ?__non_webpack_require__: require

(PS: the scheme was found in Du Niang, which is not original. Because the original text can not be found, you can record it yourself so that you can find it easily when you encounter a problem next time.)