Package detail

module-from-string

exuanbo129.4kMIT3.3.1

Load module from string using require or import.

load, module, string, require

readme

module-from-string

Load module from string using require or import.

npm GitHub Workflow Status (branch) Node.js libera manifesto

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 { Context } from 'vm';
import { TransformOptions } from 'esbuild';

interface Options {
  filename?: string
  dirname?: string
  globals?: Context
  useCurrentGlobal?: boolean
}

declare const requireFromString: (code: string, options?: Options) => any
declare const createRequireFromString: (options?: Options) => typeof requireFromString

interface ImportOptions extends Options {
  transformOptions?: TransformOptions
}

declare const importFromString: (code: string, options?: ImportOptions) => Promise<any>
declare const createImportFromString: (options?: ImportOptions) => typeof importFromString

declare const importFromStringSync: (code: string, options?: ImportOptions) => any
declare const createImportFromStringSync: (options?: ImportOptions) => typeof importFromStringSync

filename

Name, path or URL string of the virtual file for better exception stack trace.

requireFromString(
  "throw new Error('boom!')",
  { filename: '/home/foo.js' }
)
// /home/foo.js:1
// throw new Error('boom!')
// ^
//
// Error: boom!
//     at /home/foo.js:1:7
//     at ...

dirname

Path or URL string of the directory for resolving require or import from relative path.

requireFromString(
  "module.exports = require('.')",
  { dirname: path.join(__dirname, "../lib") }
) // => require('../lib')

If not specified, the default value will be the current file's directory.

globals

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

// requireFromString

vm.runInNewContext(
  code,
  {
    __dirname: contextModule.path,
    __filename: contextModule.filename,
    exports: contextModule.exports,
    module: contextModule,
    require: contextModule.require,
    ...globals
  },

Take requireFromString for example, only the module scope variables are passed into the contextObject.

In order to use other global objects that are specific to Node.js, they need to be added to option globals or set option useCurrentGlobal to true.

requireFromString(
  'module.exports = process.cwd()',
  { globals: { process } }
) // => $PWD

Note: by default the built-in objects have a different prototype.

const error = requireFromString('module.exports = new Error()')
error instanceof Error // => false

useCurrentGlobal

Default to false. If set to true, all the available variables from the current global (or globalThis) are passed into the context.

transformOptions

Function importFromString and importFromStringSync can use esbuild to transform code syntax. See esbuild Transform API for documentation.

const { greet } = importFromStringSync(
  "export const greet: () => string = () => 'hi'",
  { transformOptions: { loader: 'ts' } }
)

greet() // => 'hi'

ES modules

Dynamic import() expression of ES modules is supported by all three functions requireFromString, importFromString and importFromStringSync.

;(async () => {
  await requireFromString("module.exports = import('./index.mjs')")
})()

import statement of ES modules is supported only by asynchronous function importFromString using Node.js experimental API vm.Module.

node --experimental-vm-modules index.js

# Or use environment variable
NODE_OPTIONS=--experimental-vm-modules node index.js
// with top-level await

await importFromString("export { foo as default } from './index.mjs'")

License

MIT License © 2021 Exuanbo

changelog

Changelog

3.3.0 (2022-09-16)

Features

  • Add option filename for better exception stack trace.

3.2.1 (2022-08-02)

Bug Fixes

  • File URL was incorrectly converted to path in import() expression.
  • Error when using import statement with absolute path on Windows.

3.2.0 (2022-07-17)

Features

  • Add option useCurrentGlobal to pass all the available variable from the current global (or globalThis) into the context.
  • Add curried functions createRequireFromString, createImportFromString and createImportFromStringSync.

3.1.4 (2021-12-23)

Bug Fixes

  • import.meta.url is incorrectly set to path instead of URL string in importFromString.

Chores

  • Bump dependencies. Note that esbuild 0.14.4 adjusted its handling of default exports and the __esModule marker to improve compatibility with Webpack and Node, which may cause some changes when transforming the code from ES modules to CommonJS modules.

3.1.3 (2021-11-27)

Bug Fixes

  • Absolute path import on Windows such as C:\foo could not be resolved.

Chores

  • Bump dependencies.

3.1.2 (2021-11-07)

Chores

  • Bump and unpin dependencies.

3.1.1 (2021-08-28)

Bug Fixes

  • In the previous versions when using import statement and dynamic import() expression, the specifier would not be resolved correctly if used on Windows and the path starts with posix path separator.

Chores

  • Bump dependency esbuild from 0.12.22 to 0.12.24

3.1.0 (2021-08-21)

Bug Fixes

  • Fix problem when using import statement of ES modules.

Features

  • Add new optional option dirname to specify the directory path for resolving relative path require or import.
  • Add support for dynamic import() expression.