@speedy-js/config-loader
Version:
An out-of-box config loader with TypeScript support.
78 lines • 3.07 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.bundleRequire = void 0;
/**
* Forked from https://github.com/egoist/bundle-require/blob/main/src/index.ts
* Thanks for the great work from @egoist.
*/
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const esbuild_1 = require("esbuild");
const utils_1 = require("./utils");
const JS_EXT_RE = /\.(mjs|cjs|ts|js|tsx|jsx)$/;
function inferLoader(ext) {
if (ext === '.mjs' || ext === '.cjs')
return 'js';
return ext.slice(1);
}
const defaultGetOutputFile = (filepath) => filepath.replace(JS_EXT_RE, '.bundled.cjs');
async function bundleRequire(options) {
if (!JS_EXT_RE.test(options.filepath)) {
throw new Error(`${options.filepath} is not a valid JS file`);
}
const getOutputFile = options.getOutputFile || defaultGetOutputFile;
const outfile = getOutputFile(options.filepath);
const packageNames = (0, utils_1.getPackagesFromNodeModules)();
await (0, esbuild_1.build)({
entryPoints: [options.filepath],
outfile,
format: 'cjs',
platform: 'node',
bundle: true,
...options.esbuildOptions,
plugins: [
...(options.esbuildPlugins || []),
{
name: 'replace-path',
setup(ctx) {
ctx.onResolve({ filter: /.*/ }, args => {
const isPackage = packageNames.some(name => args.path === name || args.path.startsWith(`${name}/`));
if (isPackage) {
return {
path: args.path,
external: true,
};
}
});
ctx.onLoad({ filter: JS_EXT_RE }, async (args) => {
const contents = await fs_1.default.promises.readFile(args.path, 'utf-8');
return {
contents: contents
.replace(/\b__filename\b/g, JSON.stringify(args.path))
.replace(/\b__dirname\b/g, JSON.stringify(path_1.default.dirname(args.path)))
.replace(/\bimport\.meta\.url\b/g, JSON.stringify(`file://${args.path}`)),
loader: inferLoader(path_1.default.extname(args.path)),
};
});
},
},
],
});
let mod;
const req = options.require || require;
try {
mod = await req(outfile);
}
finally {
if (!options.preserveTemporaryFile) {
// Remove the outfile after executed
await fs_1.default.promises.unlink(outfile);
}
}
return mod;
}
exports.bundleRequire = bundleRequire;
//# sourceMappingURL=bundle-require.js.map