Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for baseUrl without paths #67

Merged
merged 1 commit into from
Nov 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions projects/project16/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "project16",
"scripts": {
"build": "tsc && tsc-alias",
"start": "npm run build && node ./dist/index.js"
}
}
4 changes: 4 additions & 0 deletions projects/project16/src/file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { emoji } from "index";
const a = new emoji;

export default a;
13 changes: 13 additions & 0 deletions projects/project16/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export class emoji {

constructor() {
const strings = [ "🥝", "🥥", "🍇", "🍈", "🍉", "🍊", "🍋", "🍌", "🍍", "🥭",
"🍎", "🍏", "🍐", "🍑", "🍒", "🍓", "🍅", "🍆", "🌽", "🌶",
"🍄", "🥑", "🥒", "🥬", "🥦", "🥔", "🧄", "🧅", "🥕", "🌭"];
console.log(strings);
}
}
import a from "file";
const b = a;
import { c } from "test/testy";
const d = c;
4 changes: 4 additions & 0 deletions projects/project16/src/test/testy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export const c = "hello";
import { emoji } from "index";

const a = new emoji;
18 changes: 18 additions & 0 deletions projects/project16/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"incremental": true,
"target": "ES2017",
"module": "commonjs",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"outDir": "./dist",
"removeComments": true,
"importHelpers": true,
"strict": true,
"baseUrl": "./src",
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
2 changes: 1 addition & 1 deletion src/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ export const mapPaths = (

export const loadConfig = (file: string): ITSConfig => {
if (!fs.existsSync(file)) {
// [BgRed_] Error: [Reset] [FgRed_]File ${file} not found[Reset]
console.log(
// [BgRed_] Error: [Reset] [FgRed_]File ${file} not found[Reset]
`\x1b[41m Error: \x1b[0m \x1b[31mFile ${file} not found\x1b[0m`
);
process.exit();
Expand Down
91 changes: 73 additions & 18 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@ export interface ReplaceTscAliasPathsOptions {
resolveFullPaths?: boolean;
}

interface Alias {
shouldPrefixMatchWildly: boolean;
prefix: string;
basePath: string;
path: string;
paths: string[];
isExtra: boolean;
}

type Assertion = (claim: any, message: string) => asserts claim;

export async function replaceTscAliasPaths(
Expand All @@ -56,7 +65,6 @@ export async function replaceTscAliasPaths(
let { baseUrl = './', outDir, paths } = loadConfig(configFile);
if (options.outDir) outDir = options.outDir;

assert(paths, 'compilerOptions.paths is not set');
assert(outDir, 'compilerOptions.outDir is not set');

const configDir: string = normalizePath(dirname(configFile));
Expand All @@ -69,7 +77,7 @@ export async function replaceTscAliasPaths(
let configDirInOutPath: string = null;
let relConfDirPathInOutPath: string;

const aliases = Object.keys(paths)
const aliases: Alias[] = Object.keys(paths)
.map((alias) => {
const _paths = paths[alias as keyof typeof paths].map((path) => {
path = path.replace(/\*$/, '').replace(/\.([mc])?ts(x)?$/, '.$1js$2');
Expand All @@ -81,8 +89,6 @@ export async function replaceTscAliasPaths(

const path = _paths[0];

const isExtra = null;
const basePath = null;
if (normalize(path).includes('..')) {
if (!configDirInOutPath) {
configDirInOutPath = getProjectDirPathInOutDir(
Expand Down Expand Up @@ -110,16 +116,14 @@ export async function replaceTscAliasPaths(
}
}
}

let prefix = alias.replace(/\*$/, '');


return {
shouldPrefixMatchWildly: alias.endsWith('*'),
prefix,
basePath,
prefix: alias.replace(/\*$/, ''),
basePath: null,
path,
paths: _paths,
isExtra
isExtra: null
};
})
.filter(({ prefix }) => prefix)
Expand Down Expand Up @@ -169,7 +173,7 @@ export async function replaceTscAliasPaths(
}: {
orig: string;
file: string;
alias: typeof aliases[0];
alias: Alias;
}): string => {
const requiredModule = orig.match(newStringRegex())?.groups?.path;
assert(
Expand All @@ -189,7 +193,7 @@ export async function replaceTscAliasPaths(
requiredModule.startsWith(alias.prefix + '/');

if (isAlias) {
let absoluteAliasPath = getAbsoluteAliasPath(alias.basePath, alias.path);
const absoluteAliasPath = getAbsoluteAliasPath(alias.basePath, alias.path);
let relativeAliasPath: string = normalizePath(
relative(dirname(file), absoluteAliasPath)
);
Expand All @@ -212,24 +216,75 @@ export async function replaceTscAliasPaths(
return orig;
};

const replaceBaseUrlImport = ({
orig,
file
}: {
orig: string;
file: string;
}): string => {
const requiredModule = orig.match(newStringRegex())?.groups?.path;
assert(
typeof requiredModule == 'string',
`Unexpected import statement pattern ${orig}`
);

// Check if import is already resolved.
if (requiredModule.startsWith('.')) {
return orig;
}

// If there are files matching the target, resolve the path.
if (existsSync(`${outPath}/${requiredModule}`) ||
existsSync(`${outPath}/${requiredModule}.js`) ||
existsSync(`${outPath}/${requiredModule}.jsx`) ||
existsSync(`${outPath}/${requiredModule}.cjs`) ||
existsSync(`${outPath}/${requiredModule}.mjs`) ||
existsSync(`${outPath}/${requiredModule}.d.ts`) ||
existsSync(`${outPath}/${requiredModule}.d.tsx`) ||
existsSync(`${outPath}/${requiredModule}.d.cts`) ||
existsSync(`${outPath}/${requiredModule}.d.mts`)) {
let relativePath: string = normalizePath(
relative(dirname(file), getAbsoluteAliasPath(outPath, ""))
);
if (!relativePath.startsWith('.')) {
relativePath = './' + relativePath;
}

const index = orig.indexOf(requiredModule);
const newImportScript =
orig.substring(0, index) +
relativePath +
(relativePath.endsWith('/')? '': '/') +
orig.substring(index);

const modulePath = newImportScript.match(newStringRegex()).groups.path;
return newImportScript.replace(modulePath, normalizePath(modulePath));
}
return orig;
}

const replaceAlias = async (
file: string,
resolveFullPath?: boolean
): Promise<boolean> => {
const code = await fsp.readFile(file, 'utf8');
let tempCode = code;
for (const alias of aliases) {
const replacementParams = {
file,
alias
};
tempCode = replaceSourceImportPaths(tempCode, file, (orig) =>
replaceImportStatement({
orig,
...replacementParams
file,
alias
})
);
}
tempCode = replaceSourceImportPaths(tempCode, file, (orig) =>
replaceBaseUrlImport({
orig,
file
})
);

// Fully resolve all import paths (not just aliased ones)
// *after* the aliases are resolved
Expand Down Expand Up @@ -272,7 +327,7 @@ export async function replaceTscAliasPaths(
const filesWatcher = watch(globPattern);
const tsconfigWatcher = watch(configFile);
const onFileChange = async (file: string) =>
replaceAlias(file, options?.resolveFullPaths);
await replaceAlias(file, options?.resolveFullPaths);
filesWatcher.on('add', onFileChange);
filesWatcher.on('change', onFileChange);
tsconfigWatcher.on('change', (_) => {
Expand Down
2 changes: 1 addition & 1 deletion src/utils/output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ export class Output {
}

error(message: string, exitProcess = false) {
// if not silent log: [BgRed_] Error: [Reset] [FgRed_]${message}[Reset][LF]
if (!this.silent)
// [BgRed_] Error: [Reset] [FgRed_]${message}[Reset][LF]
console.log(`\x1b[41m Error: \x1b[0m \x1b[31m${message}\x1b[0m\n`);
if (exitProcess) process.exit(1);
}
Expand Down