动态导入 - import() - 将代码打包为可执行文件时失败

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

我在 commonjs 环境中工作,试图动态导入 es 模块

考虑以下代码:

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
})()

语句await import('dateformat');在调试时工作正常。但是当使用 pkg 生成独立的可执行文件时,会出现以下错误:

TypeError: Invalid host defined options

有人能告诉我这是怎么回事吗?

好吧,由于某些原因,使用包 pkg 制作的节点可执行文件不支持 import() 语句。

作为临时解决方法,我为我尝试使用 rollup 导入的 es 模块制作了 cjs 替代方案。 然后,我将包复制到本地并 required 那些。

Vercel/pkg(还)不支持导入 ES6 模块。

原因似乎是 pkg 必须遍历您程序中的所有 require() 调用,以了解究竟需要将哪些内容一起打包到它创建的 exe 中。它不知道它也应该对程序中的所有 import-statements 做类似的事情。

查看:https://github.com/vercel/pkg/pull/1323