Skip to content

import-module-string v2.0.3

Latest

Choose a tag to compare

@zachleat zachleat released this 08 Aug 21:32
· 13 commits to main since this release

Adds compileAsFunction Boolean option to wrap the string code content in a function and return that function for lazy execution. This bypasses the need for any data serialization (which means we’re no longer limited to JSON.stringify-friendly data) to control the context of the executed function.

This behavior is import and export friendly (any exported things are returned from the returned function—note that export default is not currently supported here yet)

let { default: callback } = await importFromString(`export const b = 1;`, {
	compileAsFunction: true,
});

let { b } = callback();
// b === 1

You can pass in your own context for global use:

let { default: callback } = await importFromString(`export const b = myVar;`, {
	compileAsFunction: true,
});

let { b } = callback({ myVar: 99 });
// b === 99