webpack-typescript-config-dump-plugin
Version:
A webpack plugin to cache compiled typescript config on the file system
90 lines (89 loc) • 3.27 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypescriptConfigDumpPlugin = void 0;
const webpack_log_1 = __importDefault(require("webpack-log"));
const fs_1 = require("fs");
const util_1 = require("util");
const lodash_1 = require("lodash");
const log = webpack_log_1.default({ name: "wtcd" });
class TypescriptConfigDumpPlugin {
constructor(options = {}) {
this.outputPath = options.outputPath ? options.outputPath : "./";
this.name = options.name ? options.name : "tsconfig.dump";
}
apply(compiler) {
this.findTsLoader(compiler.options);
this.dumpTsConfig();
}
findTsLoader(webpackOptions) {
const rules = webpackOptions.module.rules;
lodash_1.forEach(rules, (rule) => {
if (!rule.oneOf) {
const loader = this.tryTogGetLoader(rule);
if (loader) {
this.loader = loader;
return false;
}
}
else {
lodash_1.forEach(rule.oneOf, (ext) => {
const loader = this.tryTogGetLoader(ext);
if (loader) {
this.loader = loader;
return false;
}
});
if (this.loader) {
return false;
}
}
});
}
tryTogGetLoader(rule) {
const checker = new RegExp(rule.test);
if (checker.test(".ts")) {
return lodash_1.find(rule.use, (ld) => {
const resolvedByName = [
"ts-loader",
"awesome-typescript-loader",
].includes(ld.loader);
const tsFullPath = ld.loader && ld.loader.indexOf("ts-loader") > -1;
const atsFullPath = ld.loader && ld.loader.indexOf("awesome-typescript-loader") > -1;
return resolvedByName || tsFullPath || atsFullPath;
});
}
}
dumpTsConfig() {
const configFile = lodash_1.get(this.loader, ["options", "configFile"], "../../../tsconfig.json");
const compilerOptions = lodash_1.get(this.loader, ["options", "compilerOptions"], {});
let repoConfig;
try {
repoConfig = require(configFile);
}
catch (e) {
log.warn("can't load tsconfig", configFile);
repoConfig = {};
}
const dumpCfg = lodash_1.merge({}, repoConfig, compilerOptions);
if (!fs_1.existsSync(this.outputPath)) {
try {
fs_1.mkdirSync(this.outputPath);
}
catch (err) {
log.warn("Could not create cache folder:", err);
return;
}
}
try {
const dump = util_1.inspect(dumpCfg, { depth: 10 });
fs_1.writeFileSync(`${this.outputPath}/${this.name}`, dump);
}
catch (err) {
log.warn("Could not create dump file:", err);
}
}
}
exports.TypescriptConfigDumpPlugin = TypescriptConfigDumpPlugin;