Skip to content

Commit

Permalink
fix: cjs exports has Object.prototype instead of null (#2769)
Browse files Browse the repository at this point in the history
* fix: cjs exports has Object.prototype instead of null

* chore: cleanup
  • Loading branch information
sheremet-va committed Jan 30, 2023
1 parent b666506 commit 4fc492c
Show file tree
Hide file tree
Showing 8 changed files with 36 additions and 2 deletions.
9 changes: 8 additions & 1 deletion packages/vite-node/src/client.ts
Expand Up @@ -310,8 +310,15 @@ export class ViteNodeRunner {
enumerable: false,
configurable: false,
})
// this prosxy is triggered only on exports.{name} and module.exports access
// this proxy is triggered only on exports.{name} and module.exports access
// inside the module itself. imported module is always "exports"
const cjsExports = new Proxy(exports, {
get: (target, p, receiver) => {
if (Reflect.has(target, p))
return Reflect.get(target, p, receiver)
return Reflect.get(Object.prototype, p, receiver)
},
getPrototypeOf: () => Object.prototype,
set: (_, p, value) => {
// treat "module.exports =" the same as "exports.default =" to not have nested "default.default",
// so "exports.default" becomes the actual module
Expand Down
7 changes: 7 additions & 0 deletions test/cjs/src/prototype.cjs
@@ -0,0 +1,7 @@
exports.test = () => {
// eslint-disable-next-line no-prototype-builtins
return exports.hasOwnProperty('test')
}
exports.getPrototype = () => {
return Object.getPrototypeOf(exports)
}
2 changes: 2 additions & 0 deletions test/cjs/src/prototype.d.cts
@@ -0,0 +1,2 @@
export const test: () => boolean
export const getPrototype: () => any
8 changes: 8 additions & 0 deletions test/cjs/test/prototype.test.ts
@@ -0,0 +1,8 @@
import { expect, it } from 'vitest'
import * as cjsExports from '../src/prototype.cjs'

it('has object prototype', () => {
expect(cjsExports.getPrototype()).toBe(Object.prototype)
expect(() => cjsExports.test()).not.toThrow()
expect(cjsExports.test()).toBe(true)
})
1 change: 1 addition & 0 deletions test/esm/src/prototype.d.mts
@@ -0,0 +1 @@
declare export const test: number
1 change: 1 addition & 0 deletions test/esm/src/prototype.mjs
@@ -0,0 +1 @@
export const test = 1
8 changes: 8 additions & 0 deletions test/esm/test/prototype.spec.ts
@@ -0,0 +1,8 @@
import { expect, it } from 'vitest'
import * as exports from '../src/prototype.mjs'

it('prototype is null', () => {
expect(Object.getPrototypeOf(exports)).toBe(null)
expect({}.hasOwnProperty).toBeTypeOf('function')
expect(exports.hasOwnProperty).toBeTypeOf('undefined')
})
2 changes: 1 addition & 1 deletion test/esm/vite.config.ts
Expand Up @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
deps: {
external: [/tslib/, /css-what/],
external: [/tslib/, /css-what/, /prototype\.mjs/],
registerNodeLoader: true,
},
},
Expand Down

0 comments on commit 4fc492c

Please sign in to comment.