Skip to content

Module dynamic imported from cjs output has unexpected exports. #3544

@chenjun1011

Description

@chenjun1011

Minimal repro:

// a.js
exports.createElement = function() {
  console.log('createElement')
}

// index.mjs
import { createElement } from './a';

export async function renderToHTML(requestContext) {
  createElement();
}

Esbuild config:

import * as esbuild from 'esbuild'

await esbuild.build({
  entryPoints: ['index.mjs'],
  bundle: true,
  outfile: 'bundle.js',
  target: 'node12.20.0',
  format: 'cjs'
});

Outputted bundle.js:

// ...

// a.js
var require_a = __commonJS({
  "a.js"(exports) {
    exports.createElement = function() {
      console.log("createElement");
    };
  }
});

// index.mjs
var esbuild_demo_exports = {};
__export(esbuild_demo_exports, {
  renderToHTML: () => renderToHTML
});
module.exports = __toCommonJS(esbuild_demo_exports);
var import_a = __toESM(require_a(), 1);
async function renderToHTML(requestContext) {
  (0, import_a.createElement)();
}

When use 'import()' to dynamic load bundle.js

const mod = await import('./bundle.js');
console.log('mod=>', mod);

The module loaded has an unexpected export createElement.

image

It seems although the exports passed to the module a are not node.js's native exports, it still changed the native exports. This maybe a bug in dynamic import.(The problem only occurs in the case of dynamic import)

image

If esbuild can avoid the keyword exports in __commonJS function, or provide some overriding configuration
, may solved this problem.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions