JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 30700
  • Score
    100M100P100Q167856F
  • License MIT

Load module from string, require and import.

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.

npm GitHub Workflow Status (branch) Codecov branch libera manifesto

Install

npm install module-from-string

Usage

import { requireFromString, importFromString } from 'module-from-string'

requireFromString("module.exports = 'hi'") // => 'hi'
requireFromString("exports.greet = 'hi'") // => { greet: 'hi' }

;(async () => {
  await importFromString("export default 'hi'" ) // => { default: 'hi' }
  await importFromString("export const greet = 'hi'") // => { greet: 'hi' }
})()

API

import { TransformOptions } from 'esbuild'

interface Options {
  code: string
  globals?: Record<string, unknown>
}
declare const requireFromString: (options: string | Options) => any

interface ImportOptions extends Options {
  transformOptions?: TransformOptions
}
declare const importFromString: (
  options: string | ImportOptions
) => Promise<any>
declare const importFromStringSync: (options: string | ImportOptions) => any

export { importFromString, importFromStringSync, requireFromString }

globals

Underneath the hood, module-from-string uses Node.js built-in vm module to execute code.

const contextModule = new Module(nanoid())

vm.runInNewContext(code, {
  exports: contextModule.exports,
  module: contextModule,
  require,
  ...globals
})

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({
  code: 'module.exports = process.cwd()',
  globals: { process }
})

importFromStringSync({
  code: 'export default process.cwd()',
  globals: { process }
})

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({
  code: "export const greet: () => string = () => 'hi'",
  transformOptions: { loader: 'ts' }
})

greet() // => 'hi'

License

MIT License © 2021 Exuanbo