web-infra-dev / rslib

The Rsbuild powered package build tool.
https://lib.rsbuild.dev/
MIT License
386 stars 19 forks source link

[Bug]: The CommonJS bundle can not be consumed by `import()` in Node.js #351

Open chenjiahan opened 1 day ago

chenjiahan commented 1 day ago

Version

System: OS: macOS 14.6.1 CPU: (16) arm64 Apple M3 Max Memory: 8.00 GB / 64.00 GB Shell: 5.9 - /bin/zsh Browsers: Chrome: 130.0.6723.71 Safari: 17.6 npmPackages: @rslib/core: ^0.0.15 => 0.0.15

Details

export function example(): string {
  return 'hello world';
}
import { defineConfig } from '@rslib/core';

export default defineConfig({
  lib: [
    {
      format: 'cjs',
      syntax: 'es2021',
    },
  ],
  output: { target: 'node' },
});
async function main() {
    const { example } = await import('./dist/index.cjs');
    console.log(example);
    // tsup: got "[Function: example]"
    // Rslib: got "undefined"
}
main();

Reproduce link

https://github.com/chenjiahan/rslib-repro-cjs-export

Reproduce Steps

Rslib:

tsup:

chenjiahan commented 1 day ago

This is required for ESM import in node:

// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  example
});

Ref:

fi3ework commented 1 day ago

I think we're aligned with esbuild's behavior?

https://esbuild.github.io/try/#YgAwLjI0LjAALS1idW5kbGUgLS1mb3JtYXQ9Y2pzAGUAZW50cnkudHMAZXhwb3J0IGZ1bmN0aW9uIGV4YW1wbGUoKTogc3RyaW5nIHsKICByZXR1cm4gJ2hlbGxvIHdvcmxkJzsKfQo

async function main() {
  const thing = await import('./dist/index.cjs')
  console.log(thing, thing.example)
}

Checked by manually copy to the dist.

esbuild:

Image

rslib:

Image

chenjiahan commented 1 day ago

@fi3ework --platform=node is required for esbuild

Image