-
Notifications
You must be signed in to change notification settings - Fork 293
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
Use custom ts paths resolve plugin #775
Draft
styfle
wants to merge
3
commits into
main
Choose a base branch
from
custom-paths-resolution
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,226 @@ | ||
/** | ||
* This webpack resolver is largely from Next.js | ||
* https://github.com/vercel/next.js/blob/29ab433222adc879e7ccaa23b29bed674e123ec4/packages/next/build/webpack/plugins/jsconfig-paths-plugin.ts#L1 | ||
*/ | ||
const path = require('path') | ||
|
||
const asterisk = 0x2a | ||
|
||
function hasZeroOrOneAsteriskCharacter(str) { | ||
let seenAsterisk = false | ||
for (let i = 0; i < str.length; i++) { | ||
if (str.charCodeAt(i) === asterisk) { | ||
if (!seenAsterisk) { | ||
seenAsterisk = true | ||
} else { | ||
// have already seen asterisk | ||
return false | ||
} | ||
} | ||
} | ||
return true | ||
} | ||
|
||
/** | ||
* Determines whether a path starts with a relative path component (i.e. `.` or `..`). | ||
*/ | ||
function pathIsRelative(testPath) { | ||
return /^\.\.?($|[\\/])/.test(testPath) | ||
} | ||
|
||
function tryParsePattern(pattern) { | ||
// This should be verified outside of here and a proper error thrown. | ||
const indexOfStar = pattern.indexOf('*') | ||
return indexOfStar === -1 | ||
? undefined | ||
: { | ||
prefix: pattern.substr(0, indexOfStar), | ||
suffix: pattern.substr(indexOfStar + 1), | ||
} | ||
} | ||
|
||
function isPatternMatch({ prefix, suffix }, candidate) { | ||
return ( | ||
candidate.length >= prefix.length + suffix.length && | ||
candidate.startsWith(prefix) && | ||
candidate.endsWith(suffix) | ||
) | ||
} | ||
|
||
/** Return the object corresponding to the best pattern to match `candidate`. */ | ||
function findBestPatternMatch( | ||
values, | ||
getPattern, | ||
candidate | ||
) { | ||
let matchedValue | ||
// use length of prefix as betterness criteria | ||
let longestMatchPrefixLength = -1 | ||
|
||
for (const v of values) { | ||
const pattern = getPattern(v) | ||
if ( | ||
isPatternMatch(pattern, candidate) && | ||
pattern.prefix.length > longestMatchPrefixLength | ||
) { | ||
longestMatchPrefixLength = pattern.prefix.length | ||
matchedValue = v | ||
} | ||
} | ||
|
||
return matchedValue | ||
} | ||
|
||
/** | ||
* patternStrings contains both pattern strings (containing "*") and regular strings. | ||
* Return an exact match if possible, or a pattern match, or undefined. | ||
* (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) | ||
*/ | ||
function matchPatternOrExact( | ||
patternStrings, | ||
candidate | ||
) { | ||
const patterns = [] | ||
for (const patternString of patternStrings) { | ||
if (!hasZeroOrOneAsteriskCharacter(patternString)) continue | ||
const pattern = tryParsePattern(patternString) | ||
if (pattern) { | ||
patterns.push(pattern) | ||
} else if (patternString === candidate) { | ||
// pattern was matched as is - no need to search further | ||
return patternString | ||
} | ||
} | ||
|
||
return findBestPatternMatch(patterns, (_) => _, candidate) | ||
} | ||
|
||
/** | ||
* Tests whether a value is string | ||
*/ | ||
function isString(text) { | ||
return typeof text === 'string' | ||
} | ||
|
||
/** | ||
* Given that candidate matches pattern, returns the text matching the '*'. | ||
* E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" | ||
*/ | ||
function matchedText(pattern, candidate) { | ||
return candidate.substring( | ||
pattern.prefix.length, | ||
candidate.length - pattern.suffix.length | ||
) | ||
} | ||
|
||
function patternText({ prefix, suffix }) { | ||
return `${prefix}*${suffix}` | ||
} | ||
|
||
const NODE_MODULES_REGEX = /node_modules/ | ||
|
||
class JsConfigPathsPlugin { | ||
constructor(paths, resolvedBaseUrl) { | ||
this.paths = paths | ||
this.resolvedBaseUrl = resolvedBaseUrl | ||
console.log('tsconfig.json or jsconfig.json paths: %O', paths) | ||
console.log('resolved baseUrl: %s', resolvedBaseUrl) | ||
} | ||
apply(resolver) { | ||
const paths = this.paths | ||
const pathsKeys = Object.keys(paths) | ||
|
||
// If no aliases are added bail out | ||
if (pathsKeys.length === 0) { | ||
console.log('paths are empty, bailing out') | ||
return | ||
} | ||
|
||
const baseDirectory = this.resolvedBaseUrl | ||
const target = resolver.ensureHook('resolve') | ||
resolver | ||
.getHook('described-resolve') | ||
.tapPromise( | ||
'JsConfigPathsPlugin', | ||
async (request, resolveContext) => { | ||
const moduleName = request.request | ||
|
||
// Exclude node_modules from paths support (speeds up resolving) | ||
if (request.path.match(NODE_MODULES_REGEX)) { | ||
console.log('skipping request as it is inside node_modules %s', moduleName) | ||
return | ||
} | ||
|
||
if ( | ||
path.posix.isAbsolute(moduleName) || | ||
(process.platform === 'win32' && path.win32.isAbsolute(moduleName)) | ||
) { | ||
console.log('skipping request as it is an absolute path %s', moduleName) | ||
return | ||
} | ||
|
||
if (pathIsRelative(moduleName)) { | ||
console.log('skipping request as it is a relative path %s', moduleName) | ||
return | ||
} | ||
|
||
// console.log('starting to resolve request %s', moduleName) | ||
|
||
// If the module name does not match any of the patterns in `paths` we hand off resolving to webpack | ||
const matchedPattern = matchPatternOrExact(pathsKeys, moduleName) | ||
if (!matchedPattern) { | ||
console.log('moduleName did not match any paths pattern %s', moduleName) | ||
return | ||
} | ||
|
||
const matchedStar = isString(matchedPattern) | ||
? undefined | ||
: matchedText(matchedPattern, moduleName) | ||
const matchedPatternText = isString(matchedPattern) | ||
? matchedPattern | ||
: patternText(matchedPattern) | ||
|
||
let triedPaths = [] | ||
|
||
for (const subst of paths[matchedPatternText]) { | ||
const curPath = matchedStar | ||
? subst.replace('*', matchedStar) | ||
: subst | ||
|
||
// Ensure .d.ts is not matched | ||
if (curPath.endsWith('.d.ts')) { | ||
continue | ||
} | ||
|
||
const candidate = path.join(baseDirectory, curPath) | ||
const [err, result] = await new Promise((resolve) => { | ||
const obj = Object.assign({}, request, { | ||
request: candidate, | ||
}) | ||
resolver.doResolve( | ||
target, | ||
obj, | ||
`Aliased with tsconfig.json or jsconfig.json ${matchedPatternText} to ${candidate}`, | ||
resolveContext, | ||
(resolverErr, resolverResult) => { | ||
resolve([resolverErr, resolverResult]) | ||
} | ||
) | ||
}) | ||
|
||
// There's multiple paths values possible, so we first have to iterate them all first before throwing an error | ||
if (err || result === undefined) { | ||
triedPaths.push(candidate) | ||
continue | ||
} | ||
|
||
return result | ||
} | ||
} | ||
) | ||
} | ||
} | ||
|
||
module.exports = { | ||
JsConfigPathsPlugin | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
How about using ts api to parse the config? It has type hint
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sounds good. I'll probably go with the other PR instead #777