Skip to content

Commit 7bd0d65

Browse files
committed
Support for different CWD and multi imports.
- Fixed resolving paths with different working directory than `tsconfig.json` (Use the new `cwd` option) - Fixed support for multiple imports per line
1 parent 4c997c3 commit 7bd0d65

File tree

4 files changed

+78
-43
lines changed

4 files changed

+78
-43
lines changed

CHANGELOG.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@ This file uses change log convention from [Keep a CHANGELOG].
55

66
## [Unreleased]
77

8+
## [1.3.0] - 2020-12-30
9+
### Fixed
10+
- Fixed resolving paths with different working directory than `tsconfig.json` (Use the new `cwd` option)
11+
- Fixed support for multiple imports per line
12+
813
## [1.2.0] - 2020-12-29
914
### Fixed
1015
- Fixed paths inside comments being resolved.
@@ -60,7 +65,8 @@ This file uses change log convention from [Keep a CHANGELOG].
6065
[Keep a CHANGELOG]: http://keepachangelog.com
6166
[Semantic Versioning]: http://semver.org/
6267

63-
[unreleased]: https://github.com/dhkatz/gulp-ts-alias/compare/1.2.0...HEAD
68+
[unreleased]: https://github.com/dhkatz/gulp-ts-alias/compare/1.3.0...HEAD
69+
[1.3.0]: https://github.com/dhkatz/gulp-ts-alias/compare/1.2.0...1.3.0
6470
[1.2.0]: https://github.com/dhkatz/gulp-ts-alias/compare/1.1.0...1.2.0
6571
[1.1.0]: https://github.com/dhkatz/gulp-ts-alias/compare/1.0.0...1.1.0
6672
[1.0.0]: https://github.com/dhkatz/gulp-ts-alias/compare/0.2.1...1.0.0

src/index.ts

Lines changed: 26 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -16,62 +16,41 @@ export interface TSConfig {
1616
export interface CompilerOptions {
1717
baseUrl?: string;
1818
paths: { [key: string]: string[] | undefined; };
19+
cwd?: string;
1920
}
2021

2122
export interface PluginOptions {
2223
configuration: TSConfig | CompilerOptions;
24+
cwd?: string;
2325
}
2426

2527
export type AliasPlugin = (pluginOptions: PluginOptions) => any;
2628

2729
const COMMENTED_PATTERN = /(\/\*(?:(?!\*\/).|[\n\r])*\*\/)|(\/\/[^\n\r]*(?:[\n\r]+|$))/;
30+
const IMPORT_PATTERNS = [/from (["'])(.*?)\1/, /import\((["'])(.*?)\1\)/, /require\((["'])(.*?)\1\)/];
2831

2932
function parseImports(file: ReadonlyArray<string>, dir: string): FileData[] {
30-
const results = file.map((line: string, index: number) => {
31-
const imports = findImport(line);
32-
33-
if (imports === null) {
34-
return null;
35-
}
36-
37-
return {
38-
path: dir,
39-
index,
40-
import: imports,
41-
};
42-
});
43-
44-
return results.filter((value: { path: string; index: number; import: string; } | null): value is FileData => {
45-
return value !== null && value !== undefined;
46-
});
33+
return file
34+
.map((line, index) => findImports(line)
35+
.map((i) => ({ path: dir, index, import: i })),
36+
)
37+
.reduce((acc, val) => acc.concat(val), []);
4738
}
4839

49-
function findImport(line: string): string | null {
50-
const matches = line.match(/from (["'])(.*?)\1/) || line.match(/import\((["'])(.*?)\1\)/) || line.match(/require\((["'])(.*?)\1\)/);
51-
52-
if (!matches) {
53-
return null;
54-
}
55-
40+
function findImports(line: string): string[] | null {
5641
if (line.match(COMMENTED_PATTERN)) {
57-
return null;
58-
}
59-
60-
const multiple = [/from (["'])(.*?)\1/g, /import\((["'])(.*?)\1\)/g, /require\((["'])(.*?)\1\)/g].some((exp) => {
61-
const results = line.match(exp);
62-
63-
return results && results.length > 1;
64-
});
65-
66-
if (multiple) {
67-
throw new Error('Multiple imports on the same line are currently not supported!');
42+
return [];
6843
}
6944

70-
return matches[2];
45+
return IMPORT_PATTERNS
46+
.map((pattern) => line.match(RegExp(pattern, 'g')))
47+
.reduce((acc, val) => acc.concat(val), [])
48+
.filter((value): value is any => value !== null)
49+
.map((match) => IMPORT_PATTERNS.reduce((matched, pattern) => matched || match.match(pattern), null)[2]);
7150
}
7251

7352
function resolveImports(file: ReadonlyArray<string>, imports: FileData[], options: CompilerOptions): string[] {
74-
const { baseUrl, paths } = options;
53+
const { baseUrl, paths, cwd } = options;
7554

7655
const aliases: { [key: string]: string[] | undefined } = {};
7756
for (const alias in paths) {
@@ -113,9 +92,11 @@ function resolveImports(file: ReadonlyArray<string>, imports: FileData[], option
11392
continue;
11493
}
11594

116-
let relative = path.relative(path.dirname(imported.path), baseUrl || './');
95+
const dirname = path.dirname(imported.path);
96+
let relative = path.join(path.resolve(baseUrl || './'), cwd);
97+
relative = path.relative(dirname, relative);
11798
relative = path.join(relative, resolved);
118-
relative = path.relative(path.dirname(imported.path), path.resolve(path.dirname(imported.path), relative));
99+
relative = path.relative(dirname, path.join(dirname, relative));
119100
relative = relative.replace(/\\/g, '/');
120101

121102
if (relative.length === 0 || !relative.startsWith('.')) {
@@ -145,6 +126,12 @@ const aliasPlugin: AliasPlugin = (pluginOptions: PluginOptions) => {
145126
compilerOptions.baseUrl = './';
146127
}
147128

129+
if (pluginOptions.cwd === undefined || pluginOptions.cwd === '.') {
130+
compilerOptions.cwd = './';
131+
} else {
132+
compilerOptions.cwd = pluginOptions.cwd;
133+
}
134+
148135
return ObjectStream.transform({
149136
onEntered: (args: EnteredArgs<File, File>) => {
150137
const file = args.object;

test/index.test.ts

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ interface TestCase {
1111
}
1212

1313
// tslint:disable-next-line:object-literal-key-quotes
14-
const compilerOptions: CompilerOptions = { paths: { 'MyAlias': ['MyAliasFolder/MyAliasClass'] }, baseUrl: './src' };
14+
const compilerOptions: CompilerOptions = { paths: { 'MyAlias': ['./src/MyAliasFolder/MyAliasClass'] }, baseUrl: '.' };
1515

1616
const run = async (test: TestCase): Promise<void> => {
1717
return new Promise<void>((resolve, reject) => {
@@ -73,7 +73,7 @@ import C from "../../MyAliasFolder/MyAliasClass";
7373

7474
it('should work with no baseUrl', async () => {
7575
return run({
76-
pluginOptions: { configuration: { paths: { MyAlias: ['MyAliasFolder/MyAliasClass'] } } },
76+
pluginOptions: { configuration: { paths: { MyAlias: ['src/MyAliasFolder/MyAliasClass'] } } },
7777
path: './src/FileFolder/InnerFileFolder/File.ts',
7878
input: `
7979
import A from "./asdf";
@@ -83,7 +83,7 @@ import C from "MyAlias";
8383
expected: `
8484
import A from "./asdf";
8585
import B from "./MyAlias";
86-
import C from "../../../MyAliasFolder/MyAliasClass";
86+
import C from "../../MyAliasFolder/MyAliasClass";
8787
`,
8888
});
8989
});
@@ -210,3 +210,44 @@ import B from "./MyAlias";
210210
`,
211211
});
212212
});
213+
214+
it('should support different working directories', async () => {
215+
return run({
216+
pluginOptions: { configuration: { ...compilerOptions, baseUrl: './tasks' }, cwd: '../' },
217+
path: './src/FileFolder/InnerFileFolder/File.ts',
218+
input: `
219+
import A from "./asdf";
220+
import B from "./MyAlias";
221+
import C from "MyAlias";
222+
import D from "express";
223+
`,
224+
expected: `
225+
import A from "./asdf";
226+
import B from "./MyAlias";
227+
import C from "../../MyAliasFolder/MyAliasClass";
228+
import D from "express";
229+
`,
230+
});
231+
});
232+
233+
it('should support different working directories with node_modules', async () => {
234+
return run({
235+
pluginOptions: {
236+
configuration: { ...compilerOptions, paths: { MyAlias: ['node_modules/@lib/MyAliasClass'] }, baseUrl: './tasks' },
237+
cwd: '../' ,
238+
},
239+
path: './src/FileFolder/InnerFileFolder/File.ts',
240+
input: `
241+
import A from "./asdf";
242+
import B from "./MyAlias";
243+
import C from "MyAlias";
244+
import D from "express";
245+
`,
246+
expected: `
247+
import A from "./asdf";
248+
import B from "./MyAlias";
249+
import C from "../../../node_modules/@lib/MyAliasClass";
250+
import D from "express";
251+
`,
252+
});
253+
});

tsconfig.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
"compilerOptions": {
33
/* Module/Target Options */
44
"target": "es6",
5+
"lib": ["es2019"],
56
"module": "commonjs",
67
"sourceMap": true,
78
"declaration": true,

0 commit comments

Comments
 (0)