UNPKG

esm-loader-typescript

Version:
69 lines (68 loc) 2.57 kB
// https://github.com/sebamarynissen/create-esm-loader#1-compile-typescript-on-the-fly import createLoader from 'create-esm-loader'; import { cwd } from 'node:process'; import { dirname, extname } from 'node:path'; import semver from 'semver'; import ts from 'typescript'; const NAME = 'esm-loader-typescript'; const EXT = '.ts'; let tsConfig; // create-esm-loader config const config = { resolve: (specifier, options) => { const { debug, parentURL } = options; const { href, pathname } = new URL(specifier, parentURL); if (extname(pathname) === EXT) { if (debug) console.log(`[${NAME}] resolve: ${specifier}`); return { format: semver.gte(process.versions.node, '16.12.0') ? 'module' // node>=16.12 only : undefined, url: href, }; } }, format: (url, options) => { const { debug } = options; const { pathname } = new URL(url); if (semver.gte(process.versions.node, '16.12.0')) return undefined; // node<16.12 if (extname(pathname) === EXT) { if (debug) console.log(`[${NAME}] format: ${url}`); return { format: 'module' }; } }, transform: async (source, options) => { const { debug, config = 'tsconfig.json', url } = options; const { pathname } = new URL(url); if (extname(pathname) != EXT) return; if (!tsConfig) { const configFileName = ts.findConfigFile(cwd(), ts.sys.fileExists, config); const configFile = ts.readConfigFile(configFileName, ts.sys.readFile); const compilerOptions = ts.parseJsonConfigFileContent(configFile.config, ts.sys, dirname(configFileName)); tsConfig = compilerOptions.options; tsConfig.inlineSourceMap = true; if (!tsConfig.module) tsConfig.module = ts.ModuleKind.ESNext; if (debug) console.log(`[${NAME}] using tsconfig: ${configFileName}`); } if (debug) console.log(`[${NAME}] transform: ${url}`); const { outputText } = ts.transpileModule(String(source), { compilerOptions: tsConfig, fileName: url, }); return { source: outputText }; }, }; export default config; // node loader export const { resolve, load, getFormat, // node<16.12 getSource, // node<16.12 transformSource, // node<16.12 } = await createLoader(config);