Open admartinez-edicom opened 3 months ago
That error was because elastic-apm-node adds a custom hook to replace some builtin and thrid-party modules. It redirects the require call to modules like http
and replace that with the file under itself. This code pattern is not bundle-able since it relies on a real file structure during runtime.
Your ok1
script works because it just doesn't hit those hooks. However, when express
imports http
, it hits and cannot find a ./modules/http.js
relative to the bundled file.
In summary, you'd better not bundle elastic-apm-node with either --external:elastic-apm-node
or --packages=external
.
I'm trying to use esbuild in order to bundle into a single file our production node code. However we are having some troubles with the built-in modules of node (http, https and fs but I believe it will happen with all of them).
After analyzing the generated bundle I came up with a very silly solution that is applying this regex to the final bundle:
sed 's/moduleName = filename;/moduleName = filename;\\n basedir = \\x27core:\\x27;/g'
While writing this issue we realize that it happens sometimes but I cannot determinate the reason.
I have created a repo with a sample code that behaves similar to my production code.
There are 3 files in this repo and 4 scripts:
npm run build-ok1 && node app-ok1.js
npm run build-ok2 && node app-ok2.js
npm run build-ko && node app-ko.js
--> it failsnpm run build-ko-with-fix && node app-ko-with-fix
--> it applies the regex I provide and the app works perfectlyThe error when failing is:
I came up with this solution after realizing that when the variable
basedir
is empty, the generated file use the current working directory to resolve modules. So in the "core-module-branch" I set this variable to 'core:'if (core === true) { if (hasWhitelist === true && modules.includes(filename) === false) { debug("ignoring core module not on whitelist: %s", filename); return exports3; } moduleName = filename; basedir = 'core:'; // new code } else if (hasWhitelist === true && modules.includes(filename)) { const parsedPath = path.parse(filename); moduleName = parsedPath.name; basedir = parsedPath.dir; } else {
Could you please give me any feedback? We try the --target argument with all sorts of value but all of them generate the same code