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

Export resolve paths as function #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,4 @@ lib

# next.js build output
.next
.idea
11 changes: 5 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
"name": "tscpaths",
"version": "0.0.7",
"description": "Replace absolute paths to relative paths after typescript compilation",
"main": "cjs/index.js",
"module": "lib/index.js",
"types": "lib/index.d.ts",
"main": "cjs/resolve-paths.js",
"module": "lib/resolve-paths.js",
"types": "lib/resolve-paths.d.ts",
"bin": {
"tscpaths": "cjs/index.js"
"tscpaths": "cjs/run.js"
},
"scripts": {
"build": "yarn build:esm && yarn build:cjs",
Expand Down Expand Up @@ -41,7 +41,6 @@
},
"homepage": "https://github.com/joonhocho/tscpaths#readme",
"devDependencies": {
"@types/globby": "^8.0.2",
"@types/jest": "^24.0.11",
"@types/node": "^11.12.0",
"jest": "^24.5.0",
Expand All @@ -54,6 +53,6 @@
},
"dependencies": {
"commander": "^2.19.0",
"globby": "^8.0.2"
"globby": "^9.2.0"
}
}
21 changes: 21 additions & 0 deletions src/command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// tslint:disable no-console
import * as program from 'commander';
import { IOptions, resolvePaths } from './resolve-paths';

export function command(): void {
program
.version('0.0.1')
.option('-p, --project <file>', 'path to tsconfig.json')
.option('-s, --src <path>', 'source root path')
.option('-o, --out <path>', 'output root path');

program.on('--help', () => {
console.log(`
$ tscpath -p tsconfig.json
`);
});

program.parse(process.argv);

resolvePaths(program as IOptions);
}
161 changes: 0 additions & 161 deletions src/index.ts

This file was deleted.

147 changes: 147 additions & 0 deletions src/resolve-paths.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
// tslint:disable no-console
import { existsSync, readFileSync, writeFileSync } from 'fs';
import { sync } from 'globby';
import { dirname, relative, resolve } from 'path';
import { loadConfig } from './util';

export interface IOptions {
project?: string;
src?: string;
out?: string;
}

export function resolvePaths({ project, src, out }: IOptions): void {
if (!project) {
throw new Error('--project must be specified');
}
if (!src) {
throw new Error('--src must be specified');
}

const configFile = resolve(process.cwd(), project);
console.log(`tsconfig.json: ${configFile}`);
const srcRoot = resolve(src);
console.log(`src: ${srcRoot}`);

const outRoot = out && resolve(out);
console.log(`out: ${outRoot}`);

const { baseUrl, outDir, paths } = loadConfig(configFile);

if (!baseUrl) {
throw new Error('compilerOptions.baseUrl is not set');
}
if (!paths) {
throw new Error('compilerOptions.paths is not set');
}
if (!outDir) {
throw new Error('compilerOptions.outDir is not set');
}
console.log(`baseUrl: ${baseUrl}`);
console.log(`outDir: ${outDir}`);
console.log(`paths: ${JSON.stringify(paths, null, 2)}`);

const configDir = dirname(configFile);

const basePath = resolve(configDir, baseUrl);
console.log(`basePath: ${basePath}`);

const outPath = outRoot || resolve(basePath, outDir);
console.log(`outPath: ${outPath}`);

const outFileToSrcFile = (x: string): string =>
resolve(srcRoot, relative(outPath, x));

const aliases = Object.keys(paths)
.map((alias) => ({
prefix: alias.replace(/\*$/, ''),
aliasPaths: paths[alias as keyof typeof paths].map((p) =>
resolve(basePath, p.replace(/\*$/, ''))
),
}))
.filter(({ prefix }) => prefix);
console.log(`aliases: ${JSON.stringify(aliases, null, 2)}`);

const toRelative = (from: string, x: string): string => {
const rel = relative(from, x);
return (rel.startsWith('.') ? rel : `./${rel}`).replace(/\\/g, '/');
};

const exts = ['.js', '.jsx', '.ts', '.tsx', '.d.ts', '.json'];

const absToRel = (modulePath: string, outFile: string): string => {
const alen = aliases.length;
for (let j = 0; j < alen; j += 1) {
const { prefix, aliasPaths } = aliases[j];

if (modulePath.startsWith(prefix)) {
const modulePathRel = modulePath.substring(prefix.length);
const srcFile = outFileToSrcFile(outFile);
const outRel = relative(basePath, outFile);
console.log(`${outRel} (source: ${relative(basePath, srcFile)}):`);
console.log(`\timport '${modulePath}'`);
const len = aliasPaths.length;
for (let i = 0; i < len; i += 1) {
const apath = aliasPaths[i];
const moduleSrc = resolve(apath, modulePathRel);
if (
existsSync(moduleSrc) ||
exts.some((ext) => existsSync(moduleSrc + ext))
) {
const rel = toRelative(dirname(srcFile), moduleSrc);
console.log(
`\treplacing '${modulePath}' -> '${rel}' referencing ${relative(
basePath,
moduleSrc
)}`
);
return rel;
}
}
console.log(`\tcould not replace ${modulePath}`);
}
}
return modulePath;
};

const requireRegex = /(?:import|require)\(['"]([^'"]*)['"]\)/g;
const importRegex = /(?:import|from) ['"]([^'"]*)['"]/g;

const replaceImportStatement = (
orig: string,
matched: string,
outFile: string
): string => {
const index = orig.indexOf(matched);
return (
orig.substring(0, index) +
absToRel(matched, outFile) +
orig.substring(index + matched.length)
);
};

const replaceAlias = (text: string, outFile: string): string =>
text
.replace(requireRegex, (orig, matched) =>
replaceImportStatement(orig, matched, outFile)
)
.replace(importRegex, (orig, matched) =>
replaceImportStatement(orig, matched, outFile)
);

// import relative to absolute path
const files = sync(`${outPath}/**/*.{js,jsx,ts,tsx}`, {
dot: true,
noDir: true,
} as any).map((x) => resolve(x));

const flen = files.length;
for (let i = 0; i < flen; i += 1) {
const file = files[i];
const text = readFileSync(file, 'utf8');
const newText = replaceAlias(text, file);
if (text !== newText) {
writeFileSync(file, newText, 'utf8');
}
}
}
4 changes: 4 additions & 0 deletions src/run.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#! /usr/bin/env node
import { command } from './command';

command();
Loading