@softkit/i18n
Version:
This library is a simple wrapper based on [nestjs-i18n](https://nestjs-i18n.com/)
82 lines • 3.13 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.importOrRequireFile = void 0;
const tslib_1 = require("tslib");
const node_fs_1 = tslib_1.__importDefault(require("node:fs"));
const node_path_1 = tslib_1.__importDefault(require("node:path"));
const node_url_1 = require("node:url");
async function importOrRequireFile(filePath) {
const tryToImport = async () => {
// `Function` is required to make sure the `import` statement wil stay `import` after
// transpilation and won't be converted to `require`
await new Function('return filePath => import(filePath)')()(filePath.startsWith('file://')
? filePath
: (0, node_url_1.pathToFileURL)(filePath).toString());
};
const tryToRequire = async () => {
return require(filePath);
};
const extension = filePath.slice(Math.max(0, filePath.lastIndexOf('.') + '.'.length));
switch (extension) {
case 'mjs':
case 'mts': {
return tryToImport();
}
case 'cjs':
case 'cts': {
return tryToRequire();
}
case 'js':
case 'ts': {
const packageJson = await getNearestPackageJson(filePath);
if (packageJson == undefined) {
return tryToRequire();
}
else {
const isModule = packageJson?.type === 'module';
return isModule ? tryToImport() : tryToRequire();
}
}
// No default
}
return tryToRequire();
}
exports.importOrRequireFile = importOrRequireFile;
function getNearestPackageJson(filePath) {
return new Promise((accept) => {
let currentPath = filePath;
function searchPackageJson() {
const nextPath = node_path_1.default.dirname(currentPath);
if (currentPath === nextPath)
// the top of the file tree is reached
accept(null);
else {
currentPath = nextPath;
const potentialPackageJson = node_path_1.default.join(currentPath, 'package.json');
node_fs_1.default.stat(potentialPackageJson, (err, stats) => {
if (err != undefined)
searchPackageJson();
else if (stats.isFile()) {
node_fs_1.default.readFile(potentialPackageJson, 'utf8', (err, data) => {
if (err == undefined) {
try {
accept(JSON.parse(data));
}
catch {
accept(null);
}
}
else {
accept(null);
}
});
}
else
searchPackageJson();
});
}
}
searchPackageJson();
});
}
//# sourceMappingURL=import.js.map