Skip to content

Instantly share code, notes, and snippets.

@ancientstraits
Created March 18, 2025 17:10
Show Gist options
  • Save ancientstraits/b81a406b2a8aa1bc00080494e12d6af1 to your computer and use it in GitHub Desktop.
Save ancientstraits/b81a406b2a8aa1bc00080494e12d6af1 to your computer and use it in GitHub Desktop.
Generating an Import Map
import fs from 'node:fs'
const imports = [
{ alias: 'firebase/app', path: '@firebase/app' },
{ alias: 'firebase/auth', path: '@firebase/auth' },
{ alias: 'firebase/database', path: '@firebase/database' }
]
if (!fs.existsSync('node_modules')) {
console.error('Please run `npm i`')
process.exit(1)
}
const pkgJson = path => JSON.parse(fs.readFileSync(`${path}/package.json`).toString())
const getMainPath = pkg => pkg.browser || pkg.module || undefined
function getEntryPoint(pkg, path) {
const mainPath = getMainPath(pkg)
if (mainPath === undefined) return undefined
const entryPoint = `./node_modules/${path}/${mainPath}`
if (!fs.existsSync(entryPoint)) {
console.error(`${entryPoint} is not a real file`)
process.exit(1)
}
return entryPoint
}
const importMap = {
imports: {},
// scopes: {}
}
const deps = new Set()
for (const {alias, path} of imports) {
const pkg = pkgJson(`node_modules/${path}`)
Object.keys(pkg.dependencies).forEach(dep => deps.add(dep))
// deps.add(path)
const entryPoint = getEntryPoint(pkg, path)
importMap.imports[alias] = entryPoint
importMap.imports[path] = entryPoint
}
for (const dep of deps) {
const pkg = pkgJson(`node_modules/${dep}`)
const entryPoint = getEntryPoint(pkg, dep)
importMap.imports[dep] = entryPoint
}
const indent = ' '
const stringified = JSON.stringify(importMap, undefined, 4)
.split('\n')
.map(line => `${indent}${indent}${line}`)
.join('\n')
const importmapTag = /<script type="importmap">[\s\S]*?<\/script>/
const indexHtml = fs.readFileSync('index.html').toString()
const modified = indexHtml.replace(importmapTag, `<script type="importmap">\n${stringified}\n${indent}</script>`)
fs.writeFileSync('index.html', modified)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment