Skip to content

Commit

Permalink
feat: custom extension for resolveFullPath and add regex for minified…
Browse files Browse the repository at this point in the history
… js (#203)
  • Loading branch information
axmad386 authored Nov 14, 2023
1 parent 47c162f commit 3070c3c
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 14 deletions.
16 changes: 12 additions & 4 deletions src/helpers/replacers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,18 @@ export async function importReplacers(
export async function replaceAlias(
config: IConfig,
file: string,
resolveFullPath?: boolean
resolveFullPath?: boolean,
resolveFullExtension?: string
): Promise<boolean> {
config.output.debug('Starting to replace file:', file);
const code = await fsp.readFile(file, 'utf8');
const tempCode = replaceAliasString(config, file, code, resolveFullPath);
const tempCode = replaceAliasString(
config,
file,
code,
resolveFullPath,
resolveFullExtension
);

if (code !== tempCode) {
config.output.debug('replaced file with changes:', file);
Expand All @@ -155,7 +162,8 @@ export function replaceAliasString(
config: IConfig,
file: string,
code: string,
resolveFullPath?: boolean
resolveFullPath?: boolean,
resolveFullExtension?: string
): string {
config.replacers.forEach((replacer) => {
code = replaceSourceImportPaths(code, file, (orig) =>
Expand All @@ -170,7 +178,7 @@ export function replaceAliasString(
// Fully resolve all import paths (not just aliased ones)
// *after* the aliases are resolved
if (resolveFullPath) {
code = resolveFullImportPaths(code, file);
code = resolveFullImportPaths(code, file, resolveFullExtension);
}

return code;
Expand Down
10 changes: 8 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,12 @@ export async function replaceTscAliasPaths(
const replaceList = await Promise.all(
files.map((file) =>
OpenFilesLimit(() =>
replaceAlias(config, file, options?.resolveFullPaths)
replaceAlias(
config,
file,
options?.resolveFullPaths,
options?.resolveFullExtension
)
)
)
);
Expand Down Expand Up @@ -116,7 +121,8 @@ export async function prepareSingleFileReplaceTscAliasPaths(
config,
filePath,
fileContents,
options?.resolveFullPaths
options?.resolveFullPaths,
options?.resolveFullExtension
);
};
}
1 change: 1 addition & 0 deletions src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ export interface ReplaceTscAliasPathsOptions {
verbose?: boolean;
debug?: boolean;
resolveFullPaths?: boolean;
resolveFullExtension?: '.js' | '.mjs' | '.cjs';
replacers?: string[];
output?: IOutput;
aliasTrie?: TrieNode<Alias>;
Expand Down
21 changes: 13 additions & 8 deletions src/utils/import-path-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,17 @@ const importString = `(?:${anyQuote}${pathStringContent}${anyQuote})`;
// so that they can be strung together in one big pattern.
const funcStyle = `(?:\\b(?:import|require)\\s*\\(\\s*(\\/\\*.*\\*\\/\\s*)?${importString}\\s*\\))`;
const globalStyle = `(?:\\bimport\\s+${importString})`;
const globalMinimizedStyle = `(?:\\bimport${importString})`;
const fromStyle = `(?:\\bfrom\\s+${importString})`;
const fromMinimizedStyle = `(?:\\bfrom${importString})`;
const moduleStyle = `(?:\\bmodule\\s+${importString})`;

const importRegexString = `(?:${[
funcStyle,
globalStyle,
globalMinimizedStyle,
fromStyle,
fromMinimizedStyle,
moduleStyle
].join(`|`)})`;

Expand Down Expand Up @@ -73,15 +77,15 @@ class ImportPathResolver {
* and resolve them to full filenames (including the .js extension).
* If no matching file is found for a path, leave it alone.
*/
resolveFullImportPaths() {
resolveFullImportPaths(ext = '.js') {
this.replaceSourceImportPaths((importStatement) => {
// Find substring that is just quotes
const importPathMatch = importStatement.match(newStringRegex());
if (!importPathMatch) {
return importStatement;
}
const { path, pathWithQuotes } = importPathMatch.groups;
const fullPath = normalizePath(this.resolveFullPath(path));
const fullPath = normalizePath(this.resolveFullPath(path, ext));
return importStatement.replace(
pathWithQuotes,
pathWithQuotes.replace(path, fullPath)
Expand All @@ -94,19 +98,19 @@ class ImportPathResolver {
* Given an import path, resolve the full path (including extension).
* If no corresponding file can be found, return the original path.
*/
private resolveFullPath(importPath: string) {
if (importPath.match(/\.js$/)) {
private resolveFullPath(importPath: string, ext = '.js') {
if (importPath.match(new RegExp(`\${ext}$`))) {
return importPath;
}
// Try adding the extension (if not obviously a directory)
if (!importPath.match(/[/\\]$/)) {
const asFilePath = `${importPath}.js`;
const asFilePath = `${importPath}${ext}`;
if (existsSync(resolve(this.sourceDir, asFilePath))) {
return asFilePath;
}
}
// Assume the path is a folder; try adding index.js
let asFilePath = join(importPath, 'index.js');
let asFilePath = join(importPath, 'index' + ext);
if (
(importPath.startsWith('./') || importPath === '.') &&
!asFilePath.startsWith('./')
Expand All @@ -128,8 +132,9 @@ class ImportPathResolver {
return new RegExp(importRegexString, flags);
}

static resolveFullImportPaths(code: string, path: string) {
return new ImportPathResolver(code, path).resolveFullImportPaths().source;
static resolveFullImportPaths(code: string, path: string, ext = '.js') {
return new ImportPathResolver(code, path).resolveFullImportPaths(ext)
.source;
}

static replaceSourceImportPaths(
Expand Down

0 comments on commit 3070c3c

Please sign in to comment.