Skip to content

require returns undefined in a special scenario #15507

Closed

Description

@mohas

What version of Bun is running?

1.1.38

What platform is your computer?

Linux 6.1.0-10-amd64 x86_64 unknown (alpine)

What steps can reproduce the bug?

This seems like a very internal bun issue, I have a nextjs 12 project which builds ok using yarn, but I switched to bun and I get this error only on linux, on my local windows dev machine it works ok

What is the expected behavior?

No response

What do you see instead?

#20 3.237 info  - Checking validity of types...
#20 3.798 info  - Creating an optimized production build...
#20 4.501
#20 4.501 > Build error occurred
#20 4.505 929 |                 pagesDir,
#20 4.505 930 |                 runtimeAsset: hasConcurrentFeatures ? `server/${_constants1.MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js` : undefined,
#20 4.505 931 |                 dev
#20 4.505 932 |             }),
#20 4.505 933 |             (isClient || isEdgeServer) && new _nextDropClientPagePlugin.DropClientPage(),
#20 4.505 934 |             config.outputFileTracing && !isLikeServerless && (isNodeServer || isEdgeServer) && !dev && new (require("./webpack/plugins/next-trace-entrypoints-plugin")).TraceEntryPointsPlugin({
#20 4.505                                                                                                              ^
#20 4.505 TypeError: undefined is not a constructor (evaluating 'new (require("./webpack/plugins/next-trace-entrypoints-plugin")).TraceEntryPointsPlugin({
#20 4.505           appDir: dir,
#20 4.505           esmExternals: config.experimental.esmExternals,
#20 4.505           staticImageImports: !config.images.disableStaticImages,
#20 4.505           outputFileTracingRoot: config.experimental.outputFileTracingRoot
#20 4.505         })')
#20 4.505       at /app/node_modules/next/dist/build/webpack-config.js:934:104
#20 4.505       at spawnSync (node:child_process:228:20)
#20 4.505       at 5104 (/app/node_modules/next/dist/compiled/@vercel/nft/index.js:1:97628)
#20 4.505       at __nccwpck_require__ (/app/node_modules/next/dist/compiled/@vercel/nft/index.js:12:77440)
#20 4.505       at 2821 (/app/node_modules/next/dist/compiled/@vercel/nft/index.js:1:9943)
#20 4.505       at __nccwpck_require__ (/app/node_modules/next/dist/compiled/@vercel/nft/index.js:12:77440)
#20 4.505       at 4184 (/app/node_modules/next/dist/compiled/@vercel/nft/index.js:1:45738)
#20 4.505       at __nccwpck_require__ (/app/node_modules/next/dist/compiled/@vercel/nft/index.js:12:77440)
#20 4.505
#20 4.549 error: script "build-next" exited with code 1
#20 ERROR: process "/bin/sh -c bun run build-next" did not complete successfully: exit code: 1
------
 > [builder 3/3] RUN bun run build-next:
4.505       at /app/node_modules/next/dist/build/webpack-config.js:934:104
4.505       at spawnSync (node:child_process:228:20)
4.505       at 5104 (/app/node_modules/next/dist/compiled/@vercel/nft/index.js:1:97628)
4.505       at __nccwpck_require__ (/app/node_modules/next/dist/compiled/@vercel/nft/index.js:12:77440)
4.505       at 2821 (/app/node_modules/next/dist/compiled/@vercel/nft/index.js:1:9943)
4.505       at __nccwpck_require__ (/app/node_modules/next/dist/compiled/@vercel/nft/index.js:12:77440)
4.505       at 4184 (/app/node_modules/next/dist/compiled/@vercel/nft/index.js:1:45738)
4.505       at __nccwpck_require__ (/app/node_modules/next/dist/compiled/@vercel/nft/index.js:12:77440)
4.505
4.549 error: script "build-next" exited with code 1

Additional information

this section seems to be the problem:

config.outputFileTracing && !isLikeServerless && (isNodeServer || isEdgeServer) && !dev && new (require("./webpack/plugins/next-trace-entrypoints-plugin")).TraceEntryPointsPlugin({
                appDir: dir,
                esmExternals: config.experimental.esmExternals,
                staticImageImports: !config.images.disableStaticImages,
                outputFileTracingRoot: config.experimental.outputFileTracingRoot
            })

specialy: (require("./webpack/plugins/next-trace-entrypoints-plugin")) is being evaluated to undefined

I have run some tests:

cd node_modules/next/dist/build/
bun -e "console.log(new (require(\"./webpack/plugins/next-trace-entrypoints-plugin\")).TraceEntryPointsPlugin({}))"

# returns
#TraceEntryPointsPlugin {
#  appDir: undefined,
#  entryTraces: Map {},
#  esmExternals: undefined,
#  excludeFiles: [],
#  staticImageImports: undefined,
#  tracingRoot: undefined,
#  createTraceAssets: [AsyncFunction: createTraceAssets],
#  tapfinishModules: [Function: tapfinishModules],
#  apply: [Function: apply],
#}

also

console.log(require.resolve("./webpack/plugins/next-trace-entrypoints-plugin"))
// returns /app/node_modules/next/dist/build/webpack/plugins/next-trace-entrypoints-plugin.js
// which is correct

which makes it very puzzling for me.

this is a rough source for next-trace-entrypoints-plugin.js:

"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
var _path = _interopRequireDefault(require("path"));
var _profilingPlugin = require("./profiling-plugin");
var _isError = _interopRequireDefault(require("../../../lib/is-error"));
var _nft = require("next/dist/compiled/@vercel/nft");
var _constants = require("../../../shared/lib/constants");
var _webpack = require("next/dist/compiled/webpack/webpack");
var _webpackConfig = require("../../webpack-config");
function _interopRequireDefault(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
const PLUGIN_NAME = "TraceEntryPointsPlugin";
const TRACE_IGNORES = [
    "**/*/next/dist/server/next.js",
    "**/*/next/dist/bin/next", 
];
function getModuleFromDependency(compilation, dep) {
    return compilation.moduleGraph.getModule(dep);
}
function getFilesMapFromReasons(fileList, reasons, ignoreFn) {
    // this uses the reasons tree to collect files specific to a
    // certain parent allowing us to not have to trace each parent
    // separately
    const parentFilesMap = new Map();
    function propagateToParents(parents, file, seen = new Set()) {
        for (const parent of parents || []){
            if (!seen.has(parent)) {
                seen.add(parent);
                let parentFiles = parentFilesMap.get(parent);
                if (!parentFiles) {
                    parentFiles = new Set();
                    parentFilesMap.set(parent, parentFiles);
                }
                if (!(ignoreFn == null ? void 0 : ignoreFn(file, parent))) {
                    parentFiles.add(file);
                }
                const parentReason = reasons.get(parent);
                if (parentReason == null ? void 0 : parentReason.parents) {
                    propagateToParents(parentReason.parents, file, seen);
                }
            }
        }
    }
    for (const file1 of fileList){
        const reason = reasons.get(file1);
        const isInitial = (reason == null ? void 0 : reason.type.length) === 1 && reason.type.includes("initial");
        if (!reason || !reason.parents || isInitial && reason.parents.size === 0) {
            continue;
        }
        propagateToParents(reason.parents, file1);
    }
    return parentFilesMap;
}
class TraceEntryPointsPlugin {
// class implementations
}
exports.TraceEntryPointsPlugin = TraceEntryPointsPlugin;

Now this is very interesting if I just add this line to the top of ./webpack/plugins/next-trace-entrypoints-plugin.js:

require("./webpack/plugins/next-trace-entrypoints-plugin")

everything works fine! and consequent requires to that same file will resolve, I hope this adds a little context as to what is going on here

Activity

  1. added
    bug
    on Nov 30, 2024
  2. added
    needs investigate
    and removed on Dec 5, 2024
  3. mohas commented on Jan 4, 2025

    @mohas
    Author

    What makes this hard to deal with is that this is in the source code of webpack, what I did was very hacky inside my Dockerfile as a part of my build process:

    RUN if [ -f node_modules/next/dist/build/webpack-config.js ]; then \
          sed -i '1s/.*/"use strict";\nrequire(".\/webpack\/plugins\/next-trace-entrypoints-plugin");/' node_modules/next/dist/build/webpack-config.js; \
        fi
  4. Jarred-Sumner commented on Jan 4, 2025

    @Jarred-Sumner
    Collaborator

    its very likely something to do with overriding require (which next does)

  5. added
    node.js
    ecosystem
    on Feb 8, 2025
  6. robobun commented on Jul 24, 2026

    @robobun
    Collaborator

    Fixed by #24436 (shipped in Bun v1.3.2).

    The root cause was that child_process.spawnSync ran the main event loop and drained microtasks while waiting for the child. @vercel/nft's bundled detect-libc calls spawnSync("getconf", …) at module-load time on Linux, so a concurrent getBaseWebpackConfig continuation from Promise.all could re-enter require("./webpack/plugins/next-trace-entrypoints-plugin") while it was still loading and observe TraceEntryPointsPlugin === undefined. #24436 gives spawnSync an isolated event loop so microtasks no longer fire mid-require.

    Verified on main (1.4.0-debug+df84f8db1) with a repro that reproduces the exact stack trace on 1.1.38:

    # bun 1.1.38
    FAIL: [edgeServer] TypeError: undefined is not a constructor (TraceEntryPointsPlugin=undefined)
        at main.js:12
        at spawnSync (node:child_process:228:20)
        at nft.js:4
    
    # bun main
    OK: client,server,edgeServer
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugecosystemneeds investigatenode.js

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions