Import-from-string
![GitHub stars](https://img.shields.io/github/stars/condorheroblog/import-from-string)
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);
const esm = await importFromString("export default 'Hello World!'");
console.log(esm.default);
CJS
const { requireFromString, importFromString } = require("import-from-string");
async function main() {
const cjs = requireFromString("module.exports = 'Hi World!'");
console.log(cjs);
const esm = await importFromString("export default 'Hello World!'");
console.log(esm.default);
}
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