vite-plugin / vite-plugin-commonjs

A pure JavaScript implementation for CommonJs
MIT License
96 stars 14 forks source link

Issue Title: Failed to read named export from a cjs package #34

Closed Jinjiang closed 8 months ago

Jinjiang commented 10 months ago

I found I can only read the default export from a cjs package.

Reproduction: https://github.com/Jinjiang/reproductions/tree/vite-plugin-commonjs-20230825

e.g.:

// // it works
// import { a } from 'local-debug/foo'

// it doens't work
const { a } = require('local-debug/foo')

console.log({ a })

Thanks.

Jinjiang commented 10 months ago

After more digging, I found the require() statement would be converted into code like

import __vite__cjsImportX__foo from "foo";
const __CJS__import__X__ = __vite__cjsImportX__foo;
const x = __CJS__import__X__.default || __CJS__import__X__;

which would overwrite the named imports with the default import, and then cause the issue. (If I'm not wrong).

Do you think there is any better ways to support this case?

Thanks.