UNPKG

takin

Version:

Front end engineering base toolchain and scaffold

64 lines 2.48 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.bundleMjsOrTsFile = void 0; const esbuild_1 = require("esbuild"); const fs_extra_1 = __importDefault(require("fs-extra")); const path_1 = __importDefault(require("path")); /** * 使用 esbuild 读取 ts 或 mjs 文件内容 * @param cwd - 当前工作目录 * @param fileName - 配置文件路径 * @param mjs - 是否为 mjs 文件类型 * @returns 返回解析后的代码字符串 */ async function bundleMjsOrTsFile(cwd, fileName, mjs = false) { const result = await (0, esbuild_1.build)({ absWorkingDir: cwd, entryPoints: [fileName], outfile: 'out.js', write: false, platform: 'node', target: ['node12.2.0'], bundle: true, format: mjs ? 'esm' : 'cjs', sourcemap: 'inline', metafile: true, plugins: [ { name: 'externalize-deps', setup(build) { build.onResolve({ filter: /.*/ }, (args) => { const id = args.path; if (id[0] !== '.' && !path_1.default.isAbsolute(id)) { return { external: true }; } }); } }, { name: 'replace-import-meta', setup(build) { build.onLoad({ filter: /\.[jt]s$/ }, async (args) => { const contents = await fs_extra_1.default.readFile(args.path, 'utf8'); return { loader: args.path.endsWith('.ts') ? 'ts' : 'js', contents: contents .replace(/\bimport\.meta\.url\b/g, JSON.stringify(`file://${args.path}`)) .replace(/\b__dirname\b/g, JSON.stringify(path_1.default.dirname(args.path))) .replace(/\b__filename\b/g, JSON.stringify(args.path)) }; }); } } ] }); const { text } = result.outputFiles[0]; return text; } exports.bundleMjsOrTsFile = bundleMjsOrTsFile; //# sourceMappingURL=bundleMjsOrTsFile.js.map