Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
chenjiahan opened this issue Oct 31, 2024 · 3 comments
Open
Labels
🐞 bug Something isn't working

Comments

@chenjiahan
Copy link
Member

chenjiahan commented Oct 31, 2024

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

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

export default defineConfig({
  lib: [
    {
      format: 'cjs',
      syntax: 'es2021',
    },
  ],
  output: { target: 'node' },
});
  • Create a test.mjs file to import() the dist bundle:
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:

  • pnpm run build
  • node ./test.mjs

tsup:

  • npx tsup
  • node ./test.mjs
@chenjiahan chenjiahan added the 🐞 bug Something isn't working label Oct 31, 2024
@chenjiahan
Copy link
Member Author

chenjiahan commented Oct 31, 2024

This is required for ESM import in node:

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

Ref:

@fi3ework
Copy link
Member

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
Copy link
Member Author

chenjiahan commented Oct 31, 2024

@fi3ework --platform=node is required for esbuild

Image

@chenjiahan chenjiahan changed the title [Bug]: The CommonJS bundle can not be consumed by import() [Bug]: The CommonJS bundle can not be consumed by import() in Node.js Oct 31, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🐞 bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants