Webpack打包时出现require报错问题
错误描述
- 通常问题常出现在
target: 'node'
环境中 - 编译文件中存在以如下方式使用
require
:
// for example 1:
const reload = require('require-reload')(requireFunc)
// for example 2:
function main () {
var data = require(dataPath)
}
- 打包时会报错:
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
错误解决方案
- 在编译文件中添加如下代码即可:
const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require
(PS:该方案是在度娘中找到的,并非原创,苦于已经找不到原文,因此自己记录下,以便于下次遇到问题时方便查找)