UNPKG

@serpent/common-cli

Version:

通用的 cli 相关的函数

78 lines (75 loc) 3.43 kB
import { b as __spreadArray, c as __assign } from './tslib.es6-636c4f06.mjs'; import path from 'path'; import { p as toOSPath } from './context-96dcd180.mjs'; import { w as writeFile } from './Dir-b98fddc7.mjs'; import 'module'; import 'assert'; import 'fs'; var TypedFileMap = { 'index.d.ts': { field: 'types', tpl: "export * from '<source>'" }, 'cli.cjs': { field: 'bin', tpl: "require('<source>')" }, 'cli.mjs': { field: 'bin', tpl: "import '<source>'" }, 'index.cjs': { field: 'main', tpl: "Object.defineProperty(exports, '__esModule', { value: true });\nmodule.exports = require('<source>')" }, 'index.mjs': { field: 'module', tpl: "export * from '<source>'" }, }; /** * 在指定的目录上生成一个 node 模块,常用于在 durka/vendors 下面注入新模块 */ function createPackage(nodeModulesDir, packageName, packageDetail, callback) { var name = packageName; var rootDir = path.join.apply(path, __spreadArray([nodeModulesDir], name.split('/'), false)); var jsonPath = path.join(rootDir, 'package.json'); // 下面两个变量会动态更新 var fileMap = { 'package.json': jsonPath }; var jsonDetail = __assign({ name: name, version: '1.0.0' }, packageDetail); var write = function (fileName, content) { var file = toOSPath(path.join(rootDir, fileName)); fileMap[fileName] = file; writeFile(file, (Array.isArray(content) ? content.join('\n') : content) || ''); return true; }; var writeTyped = function (file, options) { var obj = TypedFileMap[file]; var content = options.content, source = options.source, exportDefault = options.exportDefault, prefix = options.prefix, suffix = options.suffix; if (obj) { jsonDetail[obj.field] = './' + file; var tpl = obj.tpl; if (!content && source) { if (exportDefault && (file === 'index.mjs' || file === 'index.d.ts')) tpl += "\nexport { default } from '<source>'"; content = tpl.replace(/<source>/g, source); if (prefix) content = prefix + '\n' + content; if (suffix) content = content + '\n' + suffix; } } if (jsonDetail.module && !packageDetail.exports) { var mod = { import: jsonDetail.module }; if (jsonDetail.types) mod.types = jsonDetail.types; if (jsonDetail.main) mod.require = jsonDetail.main; jsonDetail.exports = { '.': mod }; } write(file, content || ''); }; callback({ rootDir: rootDir, name: name, jsonDetail: jsonDetail, jsonPath: jsonPath, fileMap: fileMap, write: write, setBinCJS: function (opts) { return writeTyped('cli.cjs', opts); }, setBinMJS: function (opts) { return writeTyped('cli.mjs', opts); }, setMainCJS: function (opts) { return writeTyped('index.cjs', opts); }, setMainMJS: function (opts) { return writeTyped('index.mjs', opts); }, setTypes: function (opts) { return writeTyped('index.d.ts', opts); }, }); writeFile(jsonPath, JSON.stringify(jsonDetail, null, 2)); return __assign(__assign({}, fileMap), { get bin() { return fileMap['cli.cjs'] || fileMap['cli.mjs']; } }); } export { createPackage as c };