Skip to content

Commit a3d3a3a

Browse files
committed
refact: some refactoring
1 parent 57b5151 commit a3d3a3a

File tree

3 files changed

+51
-99
lines changed

3 files changed

+51
-99
lines changed

package.json

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,39 @@
11
{
22
"name": "typescript-transform-paths",
33
"version": "1.0.0",
4-
"main": "lib/index.js",
5-
"types": "lib/index.d.ts",
4+
"description": "Transforms absolute imports to relative",
5+
"keywords": [],
6+
"homepage": "https://github.com/LeDDGroup/typescript-transform-paths#readme",
7+
"bugs": {
8+
"url": "https://github.com/LeDDGroup/typescript-transform-paths/issues"
9+
},
10+
"repository": {
11+
"type": "git",
12+
"url": "git+https://github.com/LeDDGroup/typescript-transform-paths.git"
13+
},
14+
"license": "ISC",
15+
"author": "",
616
"files": [
717
"lib"
818
],
19+
"main": "lib/index.js",
20+
"types": "lib/index.d.ts",
21+
"directories": {
22+
"lib": "lib",
23+
"test": "tests"
24+
},
925
"scripts": {
10-
"prepare": "npm run build",
1126
"prebuild": "rm -rf lib",
1227
"build": "tsc",
28+
"prepare": "npm run build",
1329
"release": "standard-version",
1430
"test": "ttsc -p tests/tsconfig.json && node tests/core/index.js"
1531
},
16-
"keywords": [],
17-
"author": "",
18-
"license": "ISC",
19-
"description": "Transforms absolute imports to relative",
32+
"dependencies": {},
2033
"devDependencies": {
2134
"@types/node": "^10.12.21",
2235
"standard-version": "^4.4.0",
2336
"ttypescript": "^1.5.6",
2437
"typescript": "^3.2.4"
25-
},
26-
"dependencies": {},
27-
"directories": {
28-
"lib": "lib",
29-
"test": "tests"
30-
},
31-
"repository": {
32-
"type": "git",
33-
"url": "git+https://github.com/LeDDGroup/typescript-transform-paths.git"
34-
},
35-
"bugs": {
36-
"url": "https://github.com/LeDDGroup/typescript-transform-paths/issues"
37-
},
38-
"homepage": "https://github.com/LeDDGroup/typescript-transform-paths#readme"
38+
}
3939
}

src/index.ts

Lines changed: 23 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,39 @@
1-
import ts from "typescript";
1+
import * as ts from "typescript";
22
import { dirname, resolve, relative } from "path";
33

44
const transformer = <T extends ts.Node>(_: ts.Program) => {
55
return (context: ts.TransformationContext) => (rootNode: T) => {
6-
if (!is<ts.SourceFile>(rootNode, ts.SyntaxKind.SourceFile)) {
7-
return rootNode;
8-
}
96
const compilerOptions = context.getCompilerOptions();
107
// TODO should check if baseUrl and paths are defined
118
const baseUrl = compilerOptions.baseUrl!;
129
const paths = compilerOptions.paths!;
13-
const fileDir = dirname(rootNode.fileName);
1410
const regPaths = Object.keys(paths).map(key => ({
1511
regexp: new RegExp("^" + key.replace("*", "(.*)") + "$"),
1612
resolve: paths[key][0] // TODO should check if is not empty
1713
}));
14+
let fileDir = "";
1815
function visit(node: ts.Node): ts.Node {
19-
if (is<ts.ImportDeclaration>(node, ts.SyntaxKind.ImportDeclaration)) {
20-
if (
21-
is<ts.StringLiteral>(
22-
node.moduleSpecifier,
23-
ts.SyntaxKind.StringLiteral
24-
)
25-
) {
26-
for (const path of regPaths) {
27-
const match = node.moduleSpecifier.text.match(path.regexp);
28-
if (match) {
29-
const out = path.resolve.replace(/\*/g, match[1]);
30-
const file = relative(fileDir, resolve(baseUrl, out));
31-
// If it's in the same level or below add the ./
32-
node.moduleSpecifier.text = file[0] === "." ? file : `./${file}`;
33-
break;
34-
}
35-
}
16+
if (ts.isSourceFile(node)) {
17+
fileDir = dirname(node.fileName);
18+
return ts.visitEachChild(node, visit, context);
19+
}
20+
if (
21+
ts.isImportDeclaration(node) &&
22+
ts.isStringLiteral(node.moduleSpecifier)
23+
) {
24+
for (const path of regPaths) {
25+
const match = node.moduleSpecifier.text.match(path.regexp);
26+
if (match === null) continue;
27+
const out = path.resolve.replace(/\*/g, match[1]);
28+
const file = relative(fileDir, resolve(baseUrl, out));
29+
return ts.updateImportDeclaration(
30+
node,
31+
node.decorators,
32+
node.modifiers,
33+
node.importClause,
34+
// If it's in the same level or below add the ./
35+
ts.createLiteral(file[0] === "." ? file : `./${file}`)
36+
);
3637
}
3738
}
3839
return ts.visitEachChild(node, visit, context);
@@ -41,8 +42,4 @@ const transformer = <T extends ts.Node>(_: ts.Program) => {
4142
};
4243
};
4344

44-
function is<T extends ts.Node>(node: ts.Node, kind: ts.SyntaxKind): node is T {
45-
return node.kind === kind;
46-
}
47-
4845
export default transformer;

tsconfig.json

Lines changed: 7 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,16 @@
11
{
22
"compilerOptions": {
3-
/* Basic Options */
4-
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
5-
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
6-
// "lib": [], /* Specify library files to be included in the compilation. */
7-
// "allowJs": true, /* Allow javascript files to be compiled. */
8-
// "checkJs": true, /* Report errors in .js files. */
9-
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
10-
"declaration": true, /* Generates corresponding '.d.ts' file. */
11-
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
12-
// "sourceMap": true, /* Generates corresponding '.map' file. */
13-
// "outFile": "./", /* Concatenate and emit output to single file. */
14-
"outDir": "./lib", /* Redirect output structure to the directory. */
15-
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
16-
// "composite": true, /* Enable project compilation */
17-
// "removeComments": true, /* Do not emit comments to output. */
18-
// "noEmit": true, /* Do not emit outputs. */
19-
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
20-
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
21-
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
3+
"target": "es5",
4+
"module": "commonjs",
225

23-
/* Strict Type-Checking Options */
24-
"strict": true, /* Enable all strict type-checking options. */
25-
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
26-
// "strictNullChecks": true, /* Enable strict null checks. */
27-
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
28-
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
29-
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
30-
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
31-
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
6+
"declaration": true,
327

33-
/* Additional Checks */
34-
// "noUnusedLocals": true, /* Report errors on unused locals. */
35-
// "noUnusedParameters": true, /* Report errors on unused parameters. */
36-
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
37-
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
8+
"outDir": "./lib",
9+
"rootDir": "./src",
3810

39-
/* Module Resolution Options */
40-
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
41-
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
42-
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
43-
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
44-
// "typeRoots": [], /* List of folders to include type definitions from. */
45-
// "types": [], /* Type declaration files to be included in compilation. */
46-
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
47-
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
48-
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
11+
"strict": true,
4912

50-
/* Source Map Options */
51-
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
52-
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
53-
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
54-
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
55-
56-
/* Experimental Options */
57-
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
58-
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
13+
"esModuleInterop": true
5914
},
6015
"exclude": ["tests"]
6116
}

0 commit comments

Comments
 (0)