vercel / ncc

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

Cannot bundle `@npmcli/arborist` #1162

Closed mmomtchev closed 4 months ago

mmomtchev commented 4 months ago

Steps to reproduce:

import Arborist from '@npmcli/arborist';
new Arborist();

then:

npm i @npmcli/arborist
ncc build arborist.mjs -o bonsaist.js

Result:

ncc: Version 0.38.1
ncc: Compiling file index.mjs into ESM
less arbot.cjs
Error: Module parse failed: Unexpected token (26:23)
File was processed with these loaders:
 * ./node_modules/@vercel/ncc/dist/ncc/loaders/empty-loader.js
 * ./node_modules/@vercel/ncc/dist/ncc/loaders/relocate-loader.js
 * ./node_modules/@vercel/ncc/dist/ncc/loaders/shebang-loader.js
You may need an additional loader to handle the result of these loaders.
|     npm_lifecycle_event: event,
|     npm_lifecycle_script: cmd,
>     __webpack_require__.ab + "node-gyp.js",
|   })
| 
    at /home/mmom/src/npm-update/node_modules/@vercel/ncc/dist/ncc/index.js.cache.js:38:1896272
    at /home/mmom/src/npm-update/node_modules/@vercel/ncc/dist/ncc/index.js.cache.js:38:396262
    at _done (eval at create (/home/mmom/src/npm-update/node_modules/@vercel/ncc/dist/ncc/index.js.cache.js:21:75523), <anonymous>:9:1)
    at eval (eval at create (/home/mmom/src/npm-update/node_modules/@vercel/ncc/dist/ncc/index.js.cache.js:21:75523), <anonymous>:34:22)

The problem: arborist contains the following construct:

const npm_config_node_gyp = require.resolve('node-gyp/bin/node-gyp.js');

It is used to retrieve the path from the internally installed node-gyp and to add it to the PATH. What is remarkable in this case is that even if this statement fails (it will for the transpiled bundle - there won't be a local dependency node-gyp), this will still work globally if the environment has node-gyp.

When using rollup, it is possible to make this to work without too much fiddling. I haven't found any way to make it work with ncc.

mmomtchev commented 4 months ago

There is also an issue on the arborist side: https://github.com/npm/cli/issues/4291

mmomtchev commented 4 months ago

Maybe a very first very simple step would be to emit a warning about a require.resolve and to leave it as-is - or at least make an option to force this behavior.

mmomtchev commented 4 months ago

Alas, there is no simple solution in ncc, this should be fixed in @npmcli/arborist.