Skip to content

Latest commit

 

History

History
146 lines (88 loc) · 2.97 KB

README.md

File metadata and controls

146 lines (88 loc) · 2.97 KB

Import-from-string

NPM version Downloads License GitHub stars

Load module from string using require or import.

Features

  • Support ESM and CJS environments
  • Support dynamic import
  • Support import.meta.url
  • Support access to global variables
  • No asynchronous IO operations
  • No module cache

Install

npm install import-from-string

Usage

ESM

import { importFromString, requireFromString } from "import-from-string";

const cjs = requireFromString("module.exports = 'Hi World!'");
console.log(cjs); // Hi World!

const esm = await importFromString("export default 'Hello World!'");
console.log(esm.default); // Hello World!

CJS

const { requireFromString, importFromString } = require("import-from-string");

async function main() {
	const cjs = requireFromString("module.exports = 'Hi World!'");
	console.log(cjs); // Hi World!

	const esm = await importFromString("export default 'Hello World!'");
	console.log(esm.default); // Hello World!
}

main();

API

importFromString(code, options?)

code

Type: string

The code to import.

options

filename

Type: string
Default: {Date.now()}.js

The virtual file name of the code to import.

dirname

Type: string
Default: The directory where the function is called

The virtual directory to import the code into.

transformOptions

Type: TransformOptions

esbuild transform options.

esbuildOptions

Type: BuildOptions

esbuild options.

skipBuild

Type: boolean
Default: false

skip esbuild build.

requireFromString(code, options?)

code

Type: string

The code to import.

options

filename

Type: string
Default: {Date.now()}.js

The virtual file name of the code to import.

dirname

Type: string
Default: The directory where the function is called

The virtual directory to import the code into.

appendPaths

Type: string[]
Default: []

An array of additional paths to append when resolving modules.

prependPaths

Type: string[]
Default: []

An array of additional paths to prepend when resolving modules.

Appreciation

License

MIT License © 2023-Present Condor Hero