UNPKG

me-module-utils

Version:

Me Module utils

113 lines (88 loc) 2.6 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isMeModule = isMeModule; exports.normalizeVariableName = normalizeVariableName; exports.safeReadFileSync = safeReadFileSync; exports.getMatchedExportsName = getMatchedExportsName; exports.relativeRequirePath = relativeRequirePath; var _lodash = require("lodash"); var _chalk = _interopRequireDefault(require("chalk")); var _fs = _interopRequireDefault(require("fs")); var _relative = _interopRequireDefault(require("relative")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const NODE_ENV = process.env.NODE_ENV; /** * 判断是否是me的模块 * * @param {string} code 代码 * @return {boolean} */ function isMeModule(code) { if (!(0, _lodash.isString)(code)) { return false; } return code.includes('me.provide') || code.includes('me.require'); } /** * Transform: app-module-name * => app_module_name * * @param {string} name 变量名 * @returns {string} */ function normalizeVariableName(name) { if (!name) { return ''; } name = (0, _lodash.isNumber)(name) ? String(name) : name; if (!(0, _lodash.isString)(name)) { throw new Error('Cannot normalize none String/Number type'); } return name.replace(/-/g, '_').replace(/\./, '_'); } /** * 读取文件 * * @param {string} path 文件路径 * @param {boolean} enableDebug 是否启用调试(打印日志) * @returns {string} 文件内容 */ function safeReadFileSync(path, enableDebug = false) { let content = ''; try { content = _fs.default.readFileSync(path, 'UTF8'); } catch (ex) { if (enableDebug) { console.log(_chalk.default`{yellow Could not find file: ${path}}`); } } return content; } /** * 获取模块中所有export的变量名` * * @param {string} str js脚本内容 * @returns {string[]} */ function getMatchedExportsName(str) { const MATCH_EXPORTS_VARIABLE_REGEX = /exports\.([0-9a-zA-Z_$]+)\s*=[^=]/g; let match; let matchedName = new Set(); while ((match = MATCH_EXPORTS_VARIABLE_REGEX.exec(str)) !== null) { matchedName.add(match[1]); } return Array.from(matchedName); } /** * 计算 `require` 时,两个文件的相对路径 * * @param {string} from 调用 `require` 的文件路径 * @param {string} to 被 `require` 的文件路径 * @returns {string} */ function relativeRequirePath(from, to) { const rp = (0, _relative.default)(from, to).replace(/\.js$/, ''); // 如果在当前路径下,加上 `./` return !rp.startsWith('.') ? `./${rp}` : rp; }