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

feat!: improve interchangeability with cjs #1944

Merged
merged 5 commits into from Sep 4, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 17 additions & 2 deletions packages/vite-node/src/client.ts
Expand Up @@ -235,12 +235,27 @@ export class ViteNodeRunner {
// disambiguate the `<UNIT>:/` on windows: see nodejs/node#31710
const url = pathToFileURL(fsPath).href
const meta = { url }
const exports: any = Object.create(null)
Object.defineProperty(exports, Symbol.toStringTag, {
const exportsBase: any = Object.create(null)
Object.defineProperty(exportsBase, Symbol.toStringTag, {
value: 'Module',
enumerable: false,
configurable: false,
})
const exports = new Proxy(exportsBase, {
set(target, p, value, receiver) {
const result = Reflect.set(target, p, value, receiver)
if (p !== 'default') {
if (!Reflect.has(target, 'default'))
target.default = {}

// Node also allows access of named exports via exports.default
// https://nodejs.org/api/esm.html#commonjs-namespaces
if (target.default && typeof target.default === 'object')
target.default[p] = value
}
return result
},
})

Object.assign(mod, { code: transformed, exports })

Expand Down
4 changes: 3 additions & 1 deletion test/core/test/module.test.ts
@@ -1,7 +1,7 @@
import { expect, it } from 'vitest'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
import { a, b } from '../src/module-cjs'
import cjs, { a, b } from '../src/module-cjs'
import c, { d } from '../src/module-esm'
import * as timeout from '../src/timeout'

Expand All @@ -10,6 +10,8 @@ it('doesn\'t when extending module', () => {
})

it('should work when using cjs module', () => {
expect(cjs.a).toBe(1)
expect(cjs.b).toBe(2)
expect(a).toBe(1)
expect(b).toBe(2)
})
Expand Down