takin
Version:
Front end engineering base toolchain and scaffold
86 lines • 4.37 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const chalk_1 = __importDefault(require("chalk"));
const constants_1 = require("../constants");
const errors_1 = require("../errors");
/**
* 多配置支持插件
* 1. 注入全局多配置名称 option
* 2. 命令行多配置指定校验及过滤
*/
class MultiConfigPlugin {
constructor(shouldCheckConfigNameField = true, onFiltering) {
this.name = 'TakinMultiConfigPlugin';
this.shouldCheckConfigNameField = shouldCheckConfigNameField;
this.onFiltering = onFiltering;
}
apply(runner) {
const { name: cliName, multipleConfigEnabled, multipleConfigNameField } = runner.config;
const { shouldCheckConfigNameField } = this;
// 开启多配置支持的情况
if (multipleConfigEnabled) {
// 检查是否指定了配置名称对应的字段值
if (!multipleConfigNameField) {
throw new errors_1.ConfigError(`缺少有效的配置名称字段, 请通过 ${cliName}.enableMultipleConfig 方法指定`);
}
// 添加 config 命令行支持
runner.hooks.cli.tap(this.name, function (cli) {
cli.option(`--${multipleConfigNameField} <configName>`, '指定配置名称, 如不指定则代表选择所有配置');
});
// 检查名称是否有效
// 并执行 onFiltering 回调
runner.hooks.modifyUserConfig.tapPromise(this.name, async (userConfig, command) => {
var _a;
const filters = (_a = command === null || command === void 0 ? void 0 : command.options) === null || _a === void 0 ? void 0 : _a[multipleConfigNameField];
const rawConfig = runner.config.userConfig || [];
const allFilters = runner.config.parseFilter(filters);
// 仅当存在多配置且有筛选条件时检查
if ((rawConfig === null || rawConfig === void 0 ? void 0 : rawConfig.length) && (allFilters === null || allFilters === void 0 ? void 0 : allFilters.size)) {
const validNames = [];
// 遍历并移除有效的筛选项
rawConfig.forEach((conf, i) => {
const name = conf === null || conf === void 0 ? void 0 : conf[multipleConfigNameField];
if (name != null && constants_1.NAME_REGEXP.test(String(name))) {
validNames.push(name);
}
allFilters.delete(name);
allFilters.delete(String(i));
});
// 如果筛选项有剩余, 则代表为无效的筛选项
if (allFilters.size) {
const errorMessage = validNames.length
? `可选的配置名称有 ${chalk_1.default.bold(validNames.join(', '))}`
: '请检查.';
throw new errors_1.ConfigError(chalk_1.default.red(`未找到配置: ${Array.from(allFilters).join(', ')}, ${errorMessage}`));
}
}
// 触发配置过滤回调
if (this.onFiltering)
await this.onFiltering(runner, filters);
return userConfig;
});
// 校验配置字段
if (shouldCheckConfigNameField) {
runner.hooks.registerUserConfig.tap(this.name, function (schema) {
return schema.extend({
[multipleConfigNameField]: constants_1.UserConfigSchema.name
});
});
}
}
// 未开启多配置支持的情况下仅确保 onFiltering 回调的执行即可
else {
runner.hooks.modifyUserConfig.tapPromise(this.name, async (userConfig) => {
// 触发配置过滤回调
if (this.onFiltering)
await this.onFiltering(runner);
return userConfig;
});
}
}
}
exports.default = MultiConfigPlugin;
//# sourceMappingURL=MultiConfigPlugin.js.map