@modern-js/utils
Version:
A Progressive React Framework for modern web development.
86 lines (85 loc) • 2.87 kB
JavaScript
import { isAbsolute } from "node:path";
import { pathToFileURL } from "node:url";
import { moduleResolve } from "import-meta-resolve";
import { findExists } from "./fs.mjs";
async function importPath(path, options) {
const modulePath = isAbsolute(path) ? pathToFileURL(path).href : path;
if ('development' !== process.env.NODE_ENV) return await import(modulePath, options);
{
const timestamp = Date.now();
return await import(`${modulePath}?t=${timestamp}`, options);
}
}
async function compatibleRequireESM(path, interop = true) {
if (path.endsWith('.json')) {
const res = await importPath(path, {
with: {
type: 'json'
}
});
return res.default;
}
const requiredModule = await importPath(path);
return interop ? requiredModule.default : requiredModule;
}
async function compatibleRequire(path, interop = true) {
return await compatibleRequireESM(path, interop);
}
async function loadFromProject(moduleName, appDir) {
let requiredModule;
const paths = [
appDir,
process.cwd()
];
try {
const modulePath = tryResolve(moduleName, ...paths);
{
const moduleUrl = pathToFileURL(modulePath).href;
requiredModule = await import(moduleUrl);
}
return requiredModule.default || requiredModule;
} catch (error) {
if ('MODULE_NOT_FOUND' === error.code) throw new Error(`Cannot find module ${moduleName}.`);
throw error;
}
}
const dynamicImport = new Function('modulePath', 'return import(modulePath)');
const requireExistModule = async (filename, opt)=>{
const final = {
extensions: [
'.ts',
'.js'
],
interop: true,
...opt
};
const exist = findExists(final.extensions.map((ext)=>`${filename}${ext}`));
if (!exist) return null;
return compatibleRequire(exist, final.interop);
};
const cleanRequireCache = (filelist)=>{};
const tryResolveESM = (name, ...resolvePath)=>{
const conditions = new Set([
'node',
'import',
'module',
'default'
]);
for (const p of resolvePath)try {
return moduleResolve(name, pathToFileURL(`${p}/`), conditions, false).pathname.replace(/^\/(\w)\:/, '$1:');
} catch (err) {}
const err = new Error(`Can not find module ${name}.`);
err.code = 'MODULE_NOT_FOUND';
throw err;
};
const tryResolve = (name, ...resolvePath)=>{
let filePath = '';
try {
filePath = tryResolveESM(name, ...resolvePath);
} catch (err) {
if ('MODULE_NOT_FOUND' === err.code) throw new Error(`Can not find module ${name}.`);
throw err;
}
return filePath;
};
export { cleanRequireCache, compatibleRequire, dynamicImport, loadFromProject, requireExistModule, tryResolve };