or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-require-from-string

Require module from string in Node.js

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/require-from-string@2.0.x

To install, run

npx @tessl/cli install tessl/npm-require-from-string@2.0.0

index.mddocs/

require-from-string

Load and execute Node.js modules from string content instead of files. This utility creates a new Module instance, compiles the provided JavaScript code string within that context, and returns the resulting exports. It's particularly useful for dynamic code execution, template processing, testing frameworks, and build tools that need to manipulate JavaScript code at runtime.

Package Information

  • Package Name: require-from-string
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install require-from-string

Core Imports

const requireFromString = require("require-from-string");

Basic Usage

const requireFromString = require("require-from-string");

// Simple module execution
const result = requireFromString('module.exports = 1 + 2');
console.log(result); // 3

// Module with exports object
const utils = requireFromString(`
  module.exports = {
    add: (a, b) => a + b,
    multiply: (a, b) => a * b
  };
`);
console.log(utils.add(2, 3)); // 5

Capabilities

Module Execution

Load and execute JavaScript modules from string content with optional configuration.

/**
 * Dynamically require and execute JavaScript modules from string sources
 * @param {string} code - JavaScript module code to execute (required)
 * @param {string} [filename] - Optional filename for debugging/error reporting (default: '')
 * @param {object} [opts] - Configuration options
 * @param {Array} [opts.appendPaths] - Array of paths to append to module resolution paths
 * @param {Array} [opts.prependPaths] - Array of paths to prepend to module resolution paths
 * @returns {*} The module.exports value from the executed code string
 * @throws {Error} Throws Error if code parameter is not a string
 */
function requireFromString(code, filename, opts);

Parameter overloading: When filename is an object, it's treated as the opts parameter and filename defaults to an empty string.

// Standard usage
requireFromString(code, 'debug.js', { appendPaths: [...] });

// Filename omitted, options as second parameter
requireFromString(code, { appendPaths: [...] });

Usage Examples:

const requireFromString = require("require-from-string");

// Basic execution
const simpleResult = requireFromString('module.exports = "Hello World"');
console.log(simpleResult); // "Hello World"

// With filename for better error messages
try {
  requireFromString('throw new Error("Something went wrong")', 'test-module.js');
} catch (error) {
  console.log(error.stack); // Stack trace includes 'test-module.js'
}

// With custom module resolution paths
const code = 'module.exports = require("custom-module");';
const result = requireFromString(code, 'dynamic.js', {
  prependPaths: ['/path/to/custom/modules'],
  appendPaths: ['/additional/module/path']
});

// Options-only usage (filename omitted)
const result2 = requireFromString(code, {
  appendPaths: ['/extra/modules']
});

Error Handling:

The function throws an Error with the message "code must be a string, not [typeof code]" if the first parameter is not a string.

Runtime errors in the executed code are thrown with meaningful stack traces that include the provided filename for easier debugging.

Internal Behavior:

  • Creates a new Module instance with the provided filename
  • Sets up module resolution paths by combining prependPaths, standard node_modules paths, and appendPaths
  • Compiles and executes the code string within the module context using Module._compile()
  • Cleans up by removing the temporary module from the parent's children array to prevent memory leaks
  • Returns the resulting module.exports value

Types

/**
 * Options object for configuring module resolution paths
 */
interface RequireFromStringOptions {
  /** Array of paths to append to module resolution paths */
  appendPaths?: string[];
  /** Array of paths to prepend to module resolution paths */
  prependPaths?: string[];
}