vercel / ncc

Compile a Node.js project into a single file. Supports TypeScript, binary addons, dynamic requires.
https://npmjs.com/@vercel/ncc
MIT License
9.27k stars 291 forks source link

ncc vs Serialport Part 1 - ESM #899

Open jeffrson opened 2 years ago

jeffrson commented 2 years ago

ncc apparently does not handle require inside SerialPort (https://www.npmjs.com/package/serialport) correctly in ESM mode

  1. yarn init -y
  2. yarn add serialport@^9.2.8
  3. file index.mjs
    import SerialPort from 'serialport'
  4. ncc build .\index.mjs -s -C --target es2020
  5. node dist/index.mjs

    ReferenceError: require is not defined in ES module scope, you can use import instead
    at Object.5 (file:///C:/temp/sp_test/webpack:/sp_test/node_modules/@serialport/bindings/lib/win32.js:1:1)
    at __nccwpck_require__ (file:///C:/temp/sp_test/webpack:/sp_test/webpack/bootstrap:21:1)
    at Object.851 (file:///C:/temp/sp_test/webpack:/sp_test/node_modules/@serialport/bindings/lib/index.js:6:1)
    at __nccwpck_require__ (file:///C:/temp/sp_test/webpack:/sp_test/webpack/bootstrap:21:1)
    at Object.618 (file:///C:/temp/sp_test/webpack:/sp_test/node_modules/serialport/lib/index.js:2:1)
    at __nccwpck_require__ (file:///C:/temp/sp_test/webpack:/sp_test/webpack/bootstrap:21:1)
    at file:///C:/temp/sp_test/dist/index.mjs:3253:68
    at file:///C:/temp/sp_test/dist/index.mjs:3258:3
    at ModuleJob.run (node:internal/modules/esm/module_job:197:25)
    at async Promise.all (index 0)

ncc 0.33.3

styfle commented 2 years ago

The issue seems to be coming from node-gyp-build

https://github.com/prebuild/node-gyp-build/blob/a443aead7dcc8ec613549956b780e31077e6f4c7/index.js#L5-L6

which gets compiled to

// Workaround to fix webpack's build warnings: 'the request of a dependency is an expression'
var runtimeRequire =  true ? eval("require") : 0 // eslint-disable-line