Package Exports
- module-from-string
Readme
module-from-string
Load module from string using
require
orimport
.
Install
npm install module-from-string
Usage
import {
requireFromString,
importFromString,
importFromStringSync
} from 'module-from-string'
requireFromString("module.exports = 'hi'") // => 'hi'
requireFromString("exports.greet = 'hi'") // => { greet: 'hi' }
;(async () => {
await importFromString("export default 'hi'") // => { default: 'hi' }
})()
importFromStringSync(
"export const greet = Buffer.from([0x68, 0x69]).toString('utf8')",
{ globals: { Buffer } }
) // => { greet: 'hi' }
API
import { TransformOptions } from 'esbuild'
interface Options {
globals?: Record<string, unknown>
}
declare const requireFromString: (code: string, options?: Options) => any
interface ImportOptions extends Options {
transformOptions?: TransformOptions
}
declare const importFromString: (
code: string,
options?: ImportOptions
) => Promise<any>
declare const importFromStringSync: (
code: string,
options?: ImportOptions
) => any
export { requireFromString, importFromString, importFromStringSync }
globals
Underneath the hood, module-from-string
uses Node.js built-in vm
module to execute code.
vm.runInNewContext(
code,
{
__dirname: contextModule.path,
__filename: contextModule.filename,
exports: contextModule.exports,
module: contextModule,
require: contextModule.require,
...globals
},
{ microtaskMode: 'afterEvaluate' }
)
By default, only the above variables are passed into the contextObject
. In order to use other global objects and built-in modules you need to add them to option globals
.
requireFromString(
'module.exports = process.cwd()',
{ globals: { process } }
)// => $PWD
transformOptions
Function importFromString
and importFromStringSync
use esbuild to transform ES Module syntax to CommonJS. So it can do much more by providing transform options to esbuild. See esbuild Transform API for documentation.
const { greet } = importFromStringSync(
"export const greet: () => string = () => 'hi'",
{ transformOptions: { loader: 'ts' } }
)
greet() // => 'hi'
License
MIT License © 2021 Exuanbo