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

Support module_resolution: "nodenext" #8748

Merged
merged 13 commits into from
Jul 29, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
31 changes: 30 additions & 1 deletion crates/turbopack-core/src/resolve/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1920,7 +1920,6 @@ async fn resolve_relative_request(
let mut new_path = path_pattern.clone();

let fragment_val = fragment.await?;

if !fragment_val.is_empty() {
new_path.push(Pattern::Alternatives(
once(Pattern::Constant("".into()))
Expand All @@ -1943,6 +1942,36 @@ async fn resolve_relative_request(
.collect(),
));

if options_value.enable_js_ts_rewriting {
let mut rewritten_path = path_pattern.clone();
let rewritten_path_modified =
rewritten_path.replace_final_constants(&|c: &RcStr| -> Option<Pattern> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should modify new_path

Should be outside of the if !options_value.fully_specified

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One sideeffect of that approach is that is also replaces the js that was appended via extensions:

request with appended extensions:

Alternatives([
    Constant("./src/foo.js"),
    Constant("./src/foo.js.ts"),
    Constant("./src/foo.js.js"),
    Constant("./src/foo.js.json")])

request with extensions and then the new replacement

Alternatives([
    Constant("./src/foo.ts"),
    Constant("./src/foo.tsx"),
    Constant("./src/foo.js"),
    Constant("./src/foo.js.ts"),  // <-
    Constant("./src/foo.js.ts"),  // <-
    Constant("./src/foo.js.tsx"), // <-
    Constant("./src/foo.js.js"),
    Constant("./src/foo.js.json")])

But in practice, it probably doesn't make a difference

let result = match c.rsplit_once(".") {
Some((base, "js")) => Some((
base,
vec![
Pattern::Constant(".ts".into()),
Pattern::Constant(".tsx".into()),
],
)),
Some((base, "mjs")) => Some((base, vec![Pattern::Constant(".mts".into())])),
Some((base, "cjs")) => Some((base, vec![Pattern::Constant(".cts".into())])),
_ => None,
};
result.map(|(base, replacement)| {
Pattern::Concatenation(vec![
Pattern::Constant(base.into()),
Pattern::Alternatives(replacement),
])
})
});

if rewritten_path_modified {
// Prepend the rewritten pattern to give it higher priority
new_path = Pattern::Alternatives(vec![rewritten_path, new_path])
mischnic marked this conversation as resolved.
Show resolved Hide resolved
}
}

new_path.normalize();
};

Expand Down
3 changes: 3 additions & 0 deletions crates/turbopack-core/src/resolve/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,9 @@ pub struct ResolveOptions {
pub resolved_map: Option<Vc<ResolvedMap>>,
pub before_resolve_plugins: Vec<Vc<Box<dyn BeforeResolvePlugin>>>,
pub plugins: Vec<Vc<Box<dyn AfterResolvePlugin>>>,
/// Support resolving *.js requests to *.ts files
pub enable_js_ts_rewriting: bool,
mischnic marked this conversation as resolved.
Show resolved Hide resolved

pub placeholder_for_future_extensions: (),
}

Expand Down
92 changes: 92 additions & 0 deletions crates/turbopack-core/src/resolve/pattern.rs
Original file line number Diff line number Diff line change
Expand Up @@ -627,6 +627,33 @@ impl Pattern {
new.normalize();
Pattern::alternatives([self.clone(), new])
}

/// Calls `cb` on all constants that are at the end of the pattern and
/// replaces the given final constant with the returned pattern. Returns
/// true if replacements were performed.
pub fn replace_final_constants(&mut self, cb: &impl Fn(&RcStr) -> Option<Pattern>) -> bool {
let mut replaced = false;
match self {
Pattern::Constant(c) => {
if let Some(replacement) = cb(c) {
*self = replacement;
replaced = true;
}
}
Pattern::Dynamic => {}
Pattern::Alternatives(list) => {
for i in list {
replaced = i.replace_final_constants(cb) || replaced;
}
}
Pattern::Concatenation(list) => {
if let Some(c @ Pattern::Constant(_)) = list.last_mut() {
mischnic marked this conversation as resolved.
Show resolved Hide resolved
replaced = c.replace_final_constants(cb) || replaced;
}
}
}
replaced
}
}

impl Pattern {
Expand Down Expand Up @@ -1097,6 +1124,7 @@ pub async fn read_matches(
#[cfg(test)]
mod tests {
use rstest::*;
use turbo_tasks::RcStr;

use super::Pattern;

Expand Down Expand Up @@ -1344,4 +1372,68 @@ mod tests {
) {
assert_eq!(pat.next_constants(value), expected);
}

#[test]
fn replace_final_constants() {
fn f(mut p: Pattern, cb: &impl Fn(&RcStr) -> Option<Pattern>) -> Pattern {
p.replace_final_constants(cb);
p
}

let js_to_ts_tsx = |c: &RcStr| -> Option<Pattern> {
c.strip_suffix(".js").map(|rest| {
let new_ending = Pattern::Alternatives(vec![
Pattern::Constant(".ts".into()),
Pattern::Constant(".tsx".into()),
]);
if !rest.is_empty() {
Pattern::Concatenation(vec![Pattern::Constant(rest.into()), new_ending])
} else {
new_ending
}
})
};

assert_eq!(
f(
Pattern::Concatenation(vec![
Pattern::Constant(".".into()),
Pattern::Constant("/".into()),
Pattern::Dynamic,
Pattern::Constant(".js".into()),
]),
&js_to_ts_tsx
),
Pattern::Concatenation(vec![
Pattern::Constant(".".into()),
Pattern::Constant("/".into()),
Pattern::Dynamic,
Pattern::Alternatives(vec![
Pattern::Constant(".ts".into()),
Pattern::Constant(".tsx".into()),
]),
])
);
assert_eq!(
f(
Pattern::Concatenation(vec![
Pattern::Constant(".".into()),
Pattern::Constant("/".into()),
Pattern::Constant("abc.js".into()),
]),
&js_to_ts_tsx
),
Pattern::Concatenation(vec![
Pattern::Constant(".".into()),
Pattern::Constant("/".into()),
Pattern::Concatenation(vec![
Pattern::Constant("abc".into()),
Pattern::Alternatives(vec![
Pattern::Constant(".ts".into()),
Pattern::Constant(".tsx".into()),
])
]),
])
);
}
}
12 changes: 12 additions & 0 deletions crates/turbopack-resolve/src/typescript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ pub async fn read_from_tsconfigs<T>(
pub struct TsConfigResolveOptions {
base_url: Option<Vc<FileSystemPath>>,
import_map: Option<Vc<ImportMap>>,
is_module_resolution_nodenext: bool,
}

#[turbo_tasks::value_impl]
Expand Down Expand Up @@ -318,9 +319,18 @@ pub async fn tsconfig_resolve_options(
None
};

let is_module_resolution_nodenext = read_from_tsconfigs(&configs, |json, _| {
json["compilerOptions"]["moduleResolution"]
.as_str()
.map(|module_resolution| module_resolution.eq_ignore_ascii_case("nodenext"))
})
.await?
.unwrap_or_default();

Ok(TsConfigResolveOptions {
base_url,
import_map,
is_module_resolution_nodenext,
}
.cell())
}
Expand Down Expand Up @@ -352,6 +362,8 @@ pub async fn apply_tsconfig_resolve_options(
.unwrap_or(tsconfig_import_map),
);
}
resolve_options.enable_js_ts_rewriting = tsconfig_resolve_options.is_module_resolution_nodenext;

Ok(resolve_options.cell())
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import foo from "./src/foo.js";

it("should correctly resolve explicit extensions with nodenext", () => {
expect(foo).toBe("foo");
});
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default "foo";
mischnic marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext"
}
}
Loading