Package Exports
- module-from-string
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (module-from-string) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
module-from-string
> Load module from string, require and import.
Install
npm install module-from-string
Usage
const { requireFromString, importFromString } = require('module-from-string')
requireFromString("module.exports = 'hi'") // => 'hi'
requireFromString("exports.salute = 'hi'") // => { salute: 'hi' }
importFromString({ code: "export default 'hi'" }) // => { default: 'hi' }
importFromString({ code: "export const salute = 'hi'" }) // => { salute: 'hi' }
API
import { TransformOptions } from 'esbuild'
declare const requireFromString: (
code: string,
globals?: Record<string, unknown>
) => any
interface ImprotOptions {
code: string
transformOptions?: TransformOptions
globals?: Record<string, unknown>
}
declare const importFromString: ({
code,
transformOptions,
globals
}: ImprotOptions) => any
export { importFromString, requireFromString }
globals?
Underneath the hood, it uses Node.js built-in vm
module to execute code from string.
const _module = new Module(String(new Date().valueOf()))
const context = vm.createContext({
__dirname,
__filename,
exports: _module.exports,
module: _module,
require,
...globals
})
vm.runInContext(code, context)
By default, only above variables are passed into the created Context
. In order to use other global objects you need to add them to option globals
.
requireFromString('module.exports = process.cwd()', { process })
importFromString({
code: 'export default process.cwd()',
globals: { process }
})
transformOptions?
As bundled index.d.ts
above, it uses esbuild
to transform ES Module syntax to CommonJS. So it can do much more by providing transform options to esbuild. See documentation.
const { salute } = importFromString({
code: "export const salute: string = () => 'hi'",
transformOptions: { loader: 'ts' }
})
salute() // => 'hi'
License
MIT License © 2020 Exuanbo