resolve-tilde-loader.mjs 707 Bytes
import path from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'

const shimDir = path.dirname(fileURLToPath(import.meta.url))
const projectRoot = path.resolve(shimDir, '../../..')
const mockApiUrl = pathToFileURL(path.join(shimDir, 'mock-api.mjs')).href

export async function resolve(specifier, context, nextResolve) {
  if (specifier === '~/api/api' || specifier === '~/api/api.js') {
    return nextResolve(mockApiUrl, context)
  }
  if (specifier.startsWith('~/')) {
    let mapped = path.join(projectRoot, specifier.slice(2))
    if (!path.extname(mapped)) mapped += '.js'
    return nextResolve(pathToFileURL(mapped).href, context)
  }
  return nextResolve(specifier, context)
}