Skip to content

Instantly share code, notes, and snippets.

@amatiasq
Last active Sep 23, 2021
Embed
What would you like to do?
const extensions = {
js: 'application/javascript',
ts: 'application/typescript',
jsx: 'text/jsx',
tsx: 'text/tsx',
} as const;
type Extensions = typeof extensions;
type ValidExtension = keyof Extensions;
type ValidMediaType = Extensions[ValidExtension];
export default function esm(lang: ValidMediaType) {
return (text: TemplateStringsArray, ...rest: string[]) => {
const code = String.raw(text, rest);
const metadata = `data:${lang};charset=utf-8`;
const uri = `${metadata},${encodeURIComponent(code)}`;
return import(uri);
};
}
export const js = esm(extensions.js);
export const ts = esm(extensions.ts);
export const jsx = esm(extensions.jsx);
export const tsx = esm(extensions.tsx);
export function isValidExtension(ext: string): ext is ValidExtension {
return ext in extensions;
}
import ts from "./esm.ts"
const module = await ts`export const a = "hi!"`;
console.log(module.a) // hi!
import * as esm from "./esm.ts"
const path = 'path/to/myfile.ts'
const ext = getExtensionFrom(path)
if (!esm.isValidExtension(ext)) {
throw new Error(`Invalid extension ${ext}`)
}
const content = await Deno.readTextFile(path)
const module = esm[ext]`${content}`;
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment