Use import('data:')
and import(Blob)
to execute arbitrary JavaScript strings. A simpler alternative to node-retrieve-globals
that works in more runtimes.
Available on npm
as import-module-string
.
npm install import-module-string
- Multi-runtime: tested with Node (18+), Deno (limited), Chromium, Firefox, and WebKit.
- Defers to
export
when used, otherwise implicitlyexport
all globals (viavar
,let
,const
,function
,Array
orObject
destructuring assignment,import
specifiers, etc) - Supports top-level async/await (as expected for ES modules)
- Emulates
import.meta.url
whenfilePath
option is supplied -
addRequire
option adds support forrequire()
(in Node) - Extremely limited dependency footprint (
acorn
for JS parsing only) - Supports data object to pass in data (must be JSON.stringify friendly, more serialization options may be added later)
- Subject to URL content size maximums: Chrome
512MB
, Safari2048MB
, Firefox512MB
, Firefox prior to v13732MB
Feature | Server | Browser |
---|---|---|
import('./file.js') |
✅ with adapter: "fs"
|
✅ with Import Map or adapter: "fetch"
|
import('bare') |
✅ with adapter: "fs"
|
✅ with Import Map or adapter: "fetch"
|
import('built-in') |
✅ (no adapter needed) | N/A |
require() |
✅ with addRequire option |
❌ |
import.meta.url |
✅ with filePath option |
✅ with filePath option |
Notes:
-
built-in modules are provided by the JavaScript runtime.
node:fs
is one example. -
bare
specifiers are packages referenced by their bare name. In Node this might be a package installed from npm.
Import the script first!
import { importFromString } from "import-module-string";
View the test suite file for more examples.
await importFromString(`export var a = 1;
export const c = 3;
export let b = 2;`);
// Returns
{ a: 1, c: 3, b: 2 }
import { importFromString } from "import-module-string";
await importFromString(`var a = 1;
const c = 3;
let b = 2;`);
// Returns
{ a: 1, c: 3, b: 2 }
await importFromString("const a = b;", { data: { b: 2 } });
// Returns
{ a: 2 }
await importFromString("const a = import.meta.url;", { filePath: import.meta.url });
// Returns value for import.meta.url, example shown
{ a: `file:///…` }
// `dependency.js` has the content `export default 2;`
await importFromString("import dep from './dependency.js';", {
adapter: "fs", // use "fetch" in-browser
});
// Returns
{ dep: 2 }
Uses import.meta.resolve
to resolve paths, which will also resolve using Import Maps (where available).
// `dependency.js` has the content `export default 2;`
await importFromString("import {noop} from '@zachleat/noop';", {
adapter: "fs", // use "fetch" in-browser
});
// Returns
{ noop: function() {} }
An adapter is not required.
await importFromString("import fs from 'node:fs';");
// Returns where available (`node:fs` is not typically available in browser)
{ fs: { /* … */ } }
-
v1.0.4
addadapter
option (useadapter: "fs"
oradapter: "fetch"
) to resolve imports in various environments.