Skip to content

Commit da79640

Browse files
committed
Attempt to fix relative imports
1 parent a0a194e commit da79640

File tree

2 files changed

+92
-159
lines changed

2 files changed

+92
-159
lines changed

src/index.ts

Lines changed: 30 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import path from "path"
2-
import { TransformCallback, Transform } from "stream"
3-
import ts from "typescript"
1+
import path from 'path'
2+
import { TransformCallback, Transform } from 'stream'
3+
import ts from 'typescript'
44

5-
import File = require("vinyl")
5+
import File = require('vinyl')
66

77
export type CompilerOptions = ts.CompilerOptions
88

@@ -19,8 +19,7 @@ export interface PluginOptions {
1919

2020
export type AliasPlugin = (pluginOptions: PluginOptions) => Transform
2121

22-
const COMMENTED_PATTERN =
23-
/(\/\*(?:(?!\*\/).|[\n\r])*\*\/)|(\/\/[^\n\r]*(?:[\n\r]+|$))/
22+
const COMMENTED_PATTERN = /(\/\*(?:(?!\*\/).|[\n\r])*\*\/)|(\/\/[^\n\r]*(?:[\n\r]+|$))/
2423
const IMPORT_PATTERNS = [
2524
/from (["'])(.*?)\1/g,
2625
/import\((["'])(.*?)\1\)/g,
@@ -35,11 +34,9 @@ function parseImports(file: ReadonlyArray<string>, dir: string): FileData[] {
3534
}
3635

3736
function findImports(line: string): string[] | null {
38-
line = line.replace(COMMENTED_PATTERN, "")
37+
line = line.replace(COMMENTED_PATTERN, '')
3938

40-
return IMPORT_PATTERNS.flatMap((pattern) =>
41-
[...line.matchAll(pattern)].map((match) => match[2])
42-
)
39+
return IMPORT_PATTERNS.flatMap((pattern) => [...line.matchAll(pattern)].map((match) => match[2]))
4340
}
4441

4542
function resolveImports(
@@ -54,8 +51,8 @@ function resolveImports(
5451
/* istanbul ignore else */
5552
if (paths.hasOwnProperty(alias)) {
5653
let resolved = alias
57-
if (alias.endsWith("/*")) {
58-
resolved = alias.replace("/*", "/")
54+
if (alias.endsWith('/*')) {
55+
resolved = alias.replace('/*', '/')
5956
}
6057

6158
aliases[resolved] = paths[alias]
@@ -66,16 +63,16 @@ function resolveImports(
6663
for (const imported of imports) {
6764
const line = file[imported.index]
6865

69-
let resolved = ""
66+
let resolved = ''
7067
for (const alias in aliases) {
7168
/* istanbul ignore else */
7269
if (aliases.hasOwnProperty(alias) && imported.import.startsWith(alias)) {
7370
const choices: string[] | undefined = aliases[alias]
7471

7572
if (choices !== undefined) {
7673
resolved = choices[0]
77-
if (resolved.endsWith("/*")) {
78-
resolved = resolved.replace("/*", "/")
74+
if (resolved.endsWith('/*')) {
75+
resolved = resolved.replace('/*', '/')
7976
}
8077

8178
resolved = imported.import.replace(alias, resolved)
@@ -89,32 +86,24 @@ function resolveImports(
8986
continue
9087
}
9188

92-
const dirname = path.dirname(imported.path)
93-
let relative = path.join(path.resolve(baseUrl || "./"), cwd as string)
94-
relative = path.relative(dirname, relative)
95-
relative = path.join(relative, resolved)
96-
relative = path.relative(dirname, path.join(dirname, relative))
97-
relative = relative.replace(/\\/g, "/")
89+
const base = path.join(cwd as string, path.relative(cwd as string, baseUrl || './'))
90+
const current = path.relative(base, path.dirname(imported.path))
91+
const target = path.relative(base, resolved)
9892

99-
// if (relative.length === 0 || !relative.startsWith(".")) {
100-
// relative = "./" + relative
101-
// }
93+
const relative = path.relative(current, target).replace(/\\/g, '/')
10294

10395
lines[imported.index] = line.replace(imported.import, relative)
10496
}
10597

10698
return lines
10799
}
108100

109-
function resolveConfig(
110-
config?: string | ts.CompilerOptions,
111-
cwd?: string
112-
): ts.CompilerOptions {
101+
function resolveConfig(config?: string | ts.CompilerOptions, cwd?: string): ts.CompilerOptions {
113102
if (!config) {
114103
let configPath: string | undefined
115104

116105
/* istanbul ignore if */
117-
if (process.env.NODE_ENV !== "test") {
106+
if (process.env.NODE_ENV !== 'test') {
118107
configPath = ts.findConfigFile(cwd, ts.sys.fileExists)
119108
}
120109

@@ -123,22 +112,14 @@ function resolveConfig(
123112
}
124113

125114
const configFile = ts.readConfigFile(configPath, ts.sys.readFile)
126-
const { options } = ts.parseJsonConfigFileContent(
127-
configFile.config,
128-
ts.sys,
129-
cwd
130-
)
115+
const { options } = ts.parseJsonConfigFileContent(configFile.config, ts.sys, cwd)
131116

132117
return options
133118
}
134119

135-
if (typeof config === "string") {
120+
if (typeof config === 'string') {
136121
const configFile = ts.readConfigFile(config, ts.sys.readFile)
137-
const { options } = ts.parseJsonConfigFileContent(
138-
configFile.config,
139-
ts.sys,
140-
cwd
141-
)
122+
const { options } = ts.parseJsonConfigFileContent(configFile.config, ts.sys, cwd)
142123

143124
return options
144125
}
@@ -147,35 +128,26 @@ function resolveConfig(
147128
}
148129

149130
const alias: AliasPlugin = ({ config, cwd }: PluginOptions) => {
150-
cwd = cwd === undefined ? process.cwd() : cwd === "." ? "./" : cwd
131+
cwd = cwd === undefined ? process.cwd() : cwd === '.' ? './' : cwd
151132

152133
const compilerOptions = resolveConfig(config, cwd)
153134

154135
if (!compilerOptions.paths) {
155-
throw new Error(
156-
"Unable to find the 'paths' property in the supplied configuration!"
157-
)
136+
throw new Error("Unable to find the 'paths' property in the supplied configuration!")
158137
}
159138

160-
if (
161-
compilerOptions.baseUrl === undefined ||
162-
compilerOptions.baseUrl === "."
163-
) {
164-
compilerOptions.baseUrl = "./"
139+
if (compilerOptions.baseUrl === undefined || compilerOptions.baseUrl === '.') {
140+
compilerOptions.baseUrl = './'
165141
}
166142

167143
compilerOptions.cwd = cwd
168144

169145
return new Transform({
170146
objectMode: true,
171-
transform(
172-
file: File,
173-
encoding: BufferEncoding,
174-
callback: TransformCallback
175-
) {
147+
transform(file: File, encoding: BufferEncoding, callback: TransformCallback) {
176148
/* istanbul ignore if */
177149
if (file.isStream()) {
178-
return callback(new Error("Streaming is not supported."))
150+
return callback(new Error('Streaming is not supported.'))
179151
}
180152

181153
if (file.isNull() || !file.contents) {
@@ -184,13 +156,11 @@ const alias: AliasPlugin = ({ config, cwd }: PluginOptions) => {
184156

185157
if (!file.path) {
186158
return callback(
187-
new Error(
188-
"Received file with no path. Files must have path to be resolved."
189-
)
159+
new Error('Received file with no path. Files must have path to be resolved.')
190160
)
191161
}
192162

193-
const lines = file.contents.toString().split("\n")
163+
const lines = file.contents.toString().split('\n')
194164
const imports = parseImports(lines, file.path)
195165

196166
if (imports.length === 0) {
@@ -199,7 +169,7 @@ const alias: AliasPlugin = ({ config, cwd }: PluginOptions) => {
199169

200170
const resolved = resolveImports(lines, imports, compilerOptions)
201171

202-
file.contents = Buffer.from(resolved.join("\n"))
172+
file.contents = Buffer.from(resolved.join('\n'))
203173

204174
callback(undefined, file)
205175
},

0 commit comments

Comments
 (0)