0.0.4 • Published 6 months ago

import-from-string v0.0.4

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

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 { requireFromString, importFromString } 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