vm.SourceTextModule with cachedData

34 Views Asked by At

Got TypeError when new SourceTextModule() with a cachedData option.

It says TypeError: A dynamic import callback was not specified.

But the importModuleDynamically option is clearly there.

import vm from "vm";

let context = vm.createContext({console})

async function importModuleDynamically(name) {
    let stt = new vm.SyntheticModule(['name'], function () {
        this.setExport('name', name)
    })
    await stt.link(() => null)
    await stt.evaluate()
    return stt
}

function initializeImportMeta(meta, module) {
    meta.url = module.identifier
}

let code = 'export default () => import("fs")'
let mod1 = new vm.SourceTextModule(code, {
    context,
    identifier: 'mod1',
    importModuleDynamically,
    initializeImportMeta
})

let cachedData = mod1.createCachedData()

await mod1.link(() => null)
await mod1.evaluate()
console.log(await mod1.namespace.default())


let mod2 = new vm.SourceTextModule(code, {
    context,
    identifier: 'mod1',
    cachedData,
    importModuleDynamically,
    initializeImportMeta
})

await mod2.link(() => null)
await mod2.evaluate()
console.log(await mod2.namespace.default())

console.log(mod1, mod2)

Once cachedData is set, it means import() can not longer be used any more?

0

There are 0 best solutions below