Skip to content

Instantly share code, notes, and snippets.

@wesleytodd
Last active August 15, 2023 10:01
Show Gist options
  • Save wesleytodd/4399b2351c59438db19a8ffb1f3fcdca to your computer and use it in GitHub Desktop.
Save wesleytodd/4399b2351c59438db19a8ffb1f3fcdca to your computer and use it in GitHub Desktop.
Import Map Loader
node_modules
{
"imports": {
"todayis": "node_modules/todayis/index.js"
},
"scopes": {
"node_modules/todayis": {
"english-days": "node_modules/english-days/index.json"
}
}
}
console.log(require('todayis')((day) => `Hello, today is ${day}!`))
import module from 'module'
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const importmap = require('./importmap.json')
const orig = module._resolveFilename
module._resolveFilename = (request, parent, isMain, options) => {
// Check scopes
let rent = parent
while (rent) {
if (importmap.scopes[rent.path] && importmap.scopes[rent.path][request]) {
return importmap.scopes[rent.path][request]
}
rent = rent.parent
}
// Check imports
if (importmap.imports[request]) {
return importmap.imports[request]
}
// Fall back to filesystem lookup
return orig.call(module, request, parent, isMain, options)
}
{
"name": "hello-today",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"english-days": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/english-days/-/english-days-1.0.0.tgz",
"integrity": "sha1-0xT5Wfgq8RI9DQntWpDax3q7nhU="
},
"todayis": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/todayis/-/todayis-1.0.0.tgz",
"integrity": "sha512-rIzf7H5YCvGJMrzCqyjEfwaW8Okn+/xYq5hOTZhtuq2BG13k7IY77g6Qarf5z+xo19SJMFEBm9jaYlZ7VrmdhQ==",
"requires": {
"english-days": "^1.0.0"
}
}
}
}
{
"name": "hello-today",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "node --experimental-modules --loader ./loader.mjs index.js",
"debug": "node --inspect --inspect-brk --experimental-modules --loader ./loader.mjs index.js"
},
"repository": {
"type": "git",
"url": "git+https://gist.github.com/4399b2351c59438db19a8ffb1f3fcdca.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://gist.github.com/4399b2351c59438db19a8ffb1f3fcdca"
},
"homepage": "https://gist.github.com/4399b2351c59438db19a8ffb1f3fcdca",
"dependencies": {
"todayis": "^1.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment