esbuild-plugin-alias-path
Version:
ESBuild plugin for alias path.
89 lines (85 loc) • 2.77 kB
JavaScript
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
// src/lib/normalize-options.ts
import fs from "fs-extra";
import path from "path";
function recursiveResolve(alias, cwd) {
const result = {};
for (const [k, v] of Object.entries(alias)) {
if (fs.statSync(v).isDirectory()) {
fs.readdirSync(v).forEach((fileOrDir) => {
const isStillDir = fs.statSync(path.join(v, fileOrDir)).isDirectory();
if (isStillDir) {
const nextExploreReplacementDir = path.join(v, fileOrDir);
const currentDir = path.dirname(k).replace("**", "");
const nextExploreMatchDir = path.join(currentDir, fileOrDir);
const resolved = recursiveResolve({
[nextExploreMatchDir]: nextExploreReplacementDir
}, cwd);
const [[_k, _v]] = Object.entries(resolved);
result[_k] = _v;
} else {
const replacedKey = k.endsWith("*") ? k.replace("*", fileOrDir.replace(path.extname(fileOrDir), "")) : path.join(k, fileOrDir.replace(path.extname(fileOrDir), ""));
const absoluteReplacementValue = path.resolve(v, fileOrDir);
result[replacedKey] = absoluteReplacementValue;
}
});
k.endsWith("*") && delete alias[k];
} else {
result[k] = v;
}
}
return result;
}
__name(recursiveResolve, "recursiveResolve");
function normalizeOption(options = {}) {
const alias = options.alias ?? {};
const cwd = options.cwd ?? process.cwd();
const resolvedAlias = recursiveResolve(alias, cwd);
const shouldSkipThisPlugin = options.skip ?? !Object.keys(resolvedAlias).length;
return {
alias: resolvedAlias,
skip: shouldSkipThisPlugin,
cwd
};
}
__name(normalizeOption, "normalizeOption");
// src/lib/esbuild-plugin-alias-path.ts
var pluginName = "plugin:alias-path";
function escapeNamespace(keys) {
return new RegExp(`^${keys.map((str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")}$`);
}
__name(escapeNamespace, "escapeNamespace");
var aliasPath = /* @__PURE__ */ __name((options = {}) => {
const { alias, skip } = normalizeOption(options);
if (skip) {
return {
name: pluginName,
setup() {
}
};
}
const escapedNamespace = escapeNamespace(Object.keys(alias));
return {
name: pluginName,
setup(build) {
build.onResolve({
filter: escapedNamespace
}, ({ path: fromPath }) => {
const replacedPath = alias[fromPath];
if (!replacedPath) {
return null;
}
return {
path: replacedPath
};
});
}
};
}, "aliasPath");
// src/index.ts
var src_default = aliasPath;
export {
aliasPath,
src_default as default
};