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

Leave dynamic import untouched. #935

Open 3cp opened 2 years ago

3cp commented 2 years ago

This might be asked before, but I could not find anything.

Is there a way to ask ncc to ignore and leave my dynamic import untouched?

// To be resolved at runtime
const loaded = await import(calculated_path_of_user_file);

Thanks!

styfle commented 2 years ago

Name the input file with .mjs extension or the nearest package.json should have type: module

3cp commented 2 years ago

For reference, the trick I did to bypass webpack's transpiling of dynamic import.

// Bypass webpack rewrite dynamic import.
const _import = new Function('p', 'return import(p)');
// To be resolved at runtime
const loaded = await _import(calculated_path_of_user_file);
AlexWilson-GIS commented 1 year ago

Thanks for the reference. ncc is creating a package.json file that specifies type:module, and I changed the imported module to use the .mjs file extension, but it still couldn't import. Your bypass did the trick though.

kewisch commented 2 months ago

Is there some guidance on how to handle this for third party dependencies, or maybe some import patterns that can be ignored? I have a third party code doing this:

configModule = await import(`file://${resolvedFilePath}?nonce=${nonce}`);

where ncc gives me this error:

TypeError: Cannot read properties of undefined (reading 'path')
    at /opt/homebrew/lib/node_modules/@vercel/ncc/dist/ncc/index.js.cache.js:38:266536
    at /opt/homebrew/lib/node_modules/@vercel/ncc/dist/ncc/index.js.cache.js:14:45737
    at /opt/homebrew/lib/node_modules/@vercel/ncc/dist/ncc/index.js.cache.js:38:266064
    at /opt/homebrew/lib/node_modules/@vercel/ncc/dist/ncc/index.js.cache.js:38:1892298
    at finishWithoutResolve (/opt/homebrew/lib/node_modules/@vercel/ncc/dist/ncc/index.js.cache.js:1:498106)
    at /opt/homebrew/lib/node_modules/@vercel/ncc/dist/ncc/index.js.cache.js:1:498922
    at /opt/homebrew/lib/node_modules/@vercel/ncc/dist/ncc/index.js.cache.js:1:499557
    at eval (eval at create (/opt/homebrew/lib/node_modules/@vercel/ncc/dist/ncc/index.js.cache.js:21:75523), <anonymous>:27:1)
    at /opt/homebrew/lib/node_modules/@vercel/ncc/dist/ncc/index.js.cache.js:38:646043
    at /opt/homebrew/lib/node_modules/@vercel/ncc/dist/ncc/index.js.cache.js:38:645106

I don't want to go around changing third party code with a hack as above. Since the build fails I can't just go back and undo the wrapping. Having some sort of comment that instructs ncc to ignore the import might work, since it is a lighter touch change to third party code that might not be open to hacks. Having some sort of ignore pattern would be useful.

Either way, not just throwing a cryptic error would be helpful :)