Skip to content

Fix node-gyp-build interop for CJS importers in ESM output#4

Open
vweevers wants to merge 3 commits into
biw:mainfrom
vweevers:cjs-in-esm
Open

Fix node-gyp-build interop for CJS importers in ESM output#4
vweevers wants to merge 3 commits into
biw:mainfrom
vweevers:cjs-in-esm

Conversation

@vweevers

Copy link
Copy Markdown
Contributor

Scenario: I'm consuming a native addon from a CommonJS npm package, in an ESM bundle. Problem: the vite-plugin-native-modules plugin rewrote require('node-gyp-build')(__dirname) to a require() that points at the plugin's ESM virtual native wrapper. That made the CJS package receive the namespace object instead of the native addon itself.

To make vite-plugin-native-modules work in that scenario, I had to change the addon's entry point from:

const addon = require('node-gyp-build')(__dirname)

To:

const addonWrapper = require('node-gyp-build')(__dirname)
const addon = addonWrapper.default || addonWrapper

This PR fixes it in the plugin. What I changed:

  • In src/index.ts, CJS native-loader rewrites now emit .default when the final output format is ESM.
  • Added regression coverage in test/node-gyp-build.test.ts.
  • Fixed two Windows issues while there:
    • Normalized \ paths for additionalNativeFiles (a6ed11c)
    • Relaxed test regexes so that win32 is valid (21d25af).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant