Require.resolve not resolving for target:node bundles
See original GitHub issueBug report
What is the current behavior? My goal is create a standalone bundle. (Optimization, tree shaking whatever doesn’t matter) Source code has non-standard/unusual coding (for ex. require(require.resolve) instead of require) I think that this require minimum config of webpack. Expected scenario: a commonjs script that need any node_modules package and run as portable (without any install, npm or etc.)
Here is my example code and config for target:node bundle.
index.js
const f = require.resolve("./import.js")
require(f)()
import.js
const lodash = require("lodash")
const f = () => {
console.log(lodash.add(6, 4))
}
module.exports = f
webpack.config.js
/** @type {import('webpack').Configuration} */
module.exports = {
devtool: "inline-source-map",
mode: "development",
entry: "./index.js",
target: "node",
output: {
chunkFilename: '[id].js',
globalObject: 'this',
},
optimization: {
minimize: false,
splitChunks: {
chunks: "all",
minSize: 0
},
}
}
If the current behavior is a bug, please provide the steps to reproduce.
webpack build --stats-error-details
node dist/main.js
here is the console output
D:\lab\bundle\dist\main.js:41
throw e;
^
Error: Cannot find module './import.js'
at webpackEmptyContext (D:\lab\bundle\dist\main.js:39:10)
at Object../index.js (D:\lab\bundle\dist\main.js:28:42)
at __webpack_require__ (D:\lab\bundle\dist\main.js:70:42)
at D:\lab\bundle\dist\main.js:86:121
at Function.__webpack_require__.O (D:\lab\bundle\dist\main.js:116:23)
at __webpack_require__.x (D:\lab\bundle\dist\main.js:87:54)
at Function.__webpack_require__.x (D:\lab\bundle\dist\main.js:207:20)
at D:\lab\bundle\dist\main.js:214:57
at Object.<anonymous> (D:\lab\bundle\dist\main.js:216:12)
at Module._compile (node:internal/modules/cjs/loader:1101:14) {
code: 'MODULE_NOT_FOUND'
}
What is the expected behavior? When i run as unbundled version like this
node ./index.js
I get this output
PS D:\lab\bundle> node .\index.js
10
Here is the interesting point When i look at the dist/main.js, i see import.js’s source code
/***/ "./import.js":
/*!*******************!*\
!*** ./import.js ***!
\*******************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const lodash = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js")
const f = () => {
console.log(lodash.add(6, 4))
}
module.exports = f
Other relevant information: webpack version: 5.74.0 Node.js version: 16.13.0 Operating System: Windows 10 Additional tools: no
Issue Analytics
- State:
- Created a year ago
- Comments:12 (8 by maintainers)

Top Related StackOverflow Question
Do you have
index.js?This issue had no activity for at least three months.
It’s subject to automatic issue closing if there is no activity in the next 15 days.