'Dynamic import - import() - fails when the code is packaged into an executable

I am working in a commonjs environment trying to dynamically import an es module

Consider the below code :

const mysqlController = (async function () {
    try{
        var {default:dateformat}= await import('dateformat');
        // also tried await import('../../../node_modules/dateformat/lib/dateformat.mjs')
    }
    catch(e){
        console.error('Line 31 of db_controller');
        console.error(e);
    }
// More stuff
})()

The statement await import('dateformat'); works fine when debugging. But when using pkg to produce a standalone executable, it gives the following error:

TypeError: Invalid host defined options

Could somebody tell me what is going on here?



Solution 1:[1]

Okay, for some reason node executables made with package pkg doesn't honor import() statements.

As a temporary workaround, I made cjs alternatives for the es modules which I was trying to import using rollup. Then, I copied the bundle locally and required those.

Solution 2:[2]

Vercel/pkg does not (yet) support import of ES6 modules.

The reason seems to be that pkg must traverse all require()-calls in your program to know what exactly needs to be packaged together into the exe it creates. It does not know it should do a similar thing with all and any import-statements in your program as well.

SEE: https://github.com/vercel/pkg/pull/1323

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sjsam
Solution 2 Panu Logic