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

fix(es/module): Fix resolving of dependencies #8533

Merged
merged 27 commits into from
Jan 21, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion crates/swc/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -619,7 +619,7 @@ impl Options {
&plugin_name,
)?;

let path = if let FileName::Real(value) = resolved_path {
let path = if let FileName::Real(value) = resolved_path.filename {
value
} else {
anyhow::bail!("Failed to resolve plugin path: {:?}", resolved_path);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
import styles from "./foo.ts/index.js";
import styles from "./foo.ts/index";
console.log(styles);
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
import { NekoRoute } from "./src/lib/structures/route/index.js";
import { NekoRoute } from "./src/lib/structures/route";
console.log(NekoRoute);
2 changes: 1 addition & 1 deletion crates/swc/tests/fixture/issues-7xxx/7829/1/output/1.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
import { fn } from "./libs/pkg/src";
import { fn } from "./libs/pkg/src/index.ts";
console.log(fn);
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
const _a = require("./packages/a/src/index.js");
const _a = require("./packages/a/src/index.ts");
console.log(`${(0, _a.displayA)()}`);
14 changes: 14 additions & 0 deletions crates/swc/tests/fixture/issues-8xxx/8184/1/input/.swcrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": true
},
"baseUrl": ".",
"paths": {
"~/*": [
"./src/*"
]
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import React from 'react';
import PropTypes from 'prop-types';

const a = props => {
return (
<div>

</div>
);
};

a.propTypes = {

};

export default a;
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import React from 'react';
import PropTypes from 'prop-types';

const b = props => {
return (
<div>

</div>
);
};

b.propTypes = {

};

export default b;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default (a) => a
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import * as React from 'react';

interface IAppProps {
}

const App: React.FunctionComponent<IAppProps> = (props) => {
return <div>123</div>;
};

export default App;
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import a from '~/a';
import b from '~/b';
import c from '~/c';
import d from '~/d';

console.log(a, b, c, d);
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import React from "react";
var b = function(props) {
return /*#__PURE__*/ React.createElement("div", null);
};
b.propTypes = {};
export default b;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function(a) {
return a;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import * as React from "react";
var App = function(props) {
return /*#__PURE__*/ React.createElement("div", null, "123");
};
export default App;
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import a from "./a";
import b from "./b";
import c from "./c";
import d from "./d";
console.log(a, b, c, d);
18 changes: 11 additions & 7 deletions crates/swc_bundler/examples/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use swc_bundler::{BundleKind, Bundler, Config, Hook, Load, ModuleData, ModuleRec
use swc_common::{sync::Lrc, FileName, FilePathMapping, Globals, SourceMap, Span};
use swc_ecma_ast::KeyValueProp;
use swc_ecma_codegen::{text_writer::JsWriter, Emitter};
use swc_ecma_loader::resolve::Resolution;
use swc_ecma_parser::{parse_file_as_module, Syntax};

fn main() {
Expand Down Expand Up @@ -87,7 +88,7 @@ impl Load for PathLoader {
struct PathResolver;

impl Resolve for PathResolver {
fn resolve(&self, base: &FileName, module_specifier: &str) -> Result<FileName, Error> {
fn resolve(&self, base: &FileName, module_specifier: &str) -> Result<Resolution, Error> {
assert!(
module_specifier.starts_with('.'),
"We are not using node_modules within this example"
Expand All @@ -98,12 +99,15 @@ impl Resolve for PathResolver {
_ => unreachable!(),
};

Ok(FileName::Real(
base.parent()
.unwrap()
.join(module_specifier)
.with_extension("js"),
))
Ok(Resolution {
filename: FileName::Real(
base.parent()
.unwrap()
.join(module_specifier)
.with_extension("js"),
),
slug: None,
})
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/swc_bundler/src/bundler/finalize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ where
.resolver
.resolve(&FileName::Real(self.base.clone()), &import.src.value)
{
Ok(v) => match v {
Ok(v) => match v.filename {
FileName::Real(v) => v,
_ => panic!("rename_bundles called with non-path module"),
},
Expand Down
1 change: 1 addition & 0 deletions crates/swc_bundler/src/bundler/import/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ where
let path = self
.resolver
.resolve(base, module_specifier)
.map(|v| v.filename)
.with_context(|| format!("failed to resolve {} from {}", module_specifier, base))?;

let path = Lrc::new(path);
Expand Down
8 changes: 6 additions & 2 deletions crates/swc_bundler/src/bundler/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use anyhow::Error;
use indexmap::IndexMap;
use swc_common::{collections::ARandomState, sync::Lrc, FileName, SourceMap, Span, GLOBALS};
use swc_ecma_ast::*;
use swc_ecma_loader::resolve::Resolution;
use swc_ecma_parser::{lexer::Lexer, Parser, StringInput};
use swc_ecma_utils::drop_span;
use swc_ecma_visit::VisitMutWith;
Expand Down Expand Up @@ -52,7 +53,7 @@ impl Load for Loader {
pub struct Resolver;

impl Resolve for Resolver {
fn resolve(&self, _: &FileName, s: &str) -> Result<FileName, Error> {
fn resolve(&self, _: &FileName, s: &str) -> Result<Resolution, Error> {
assert!(s.starts_with("./"));

let path = PathBuf::from(s.to_string())
Expand All @@ -61,7 +62,10 @@ impl Resolve for Resolver {
.unwrap()
.into();

Ok(FileName::Real(path))
Ok(Resolution {
filename: FileName::Real(path),
slug: None,
})
}
}

Expand Down
15 changes: 12 additions & 3 deletions crates/swc_bundler/tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use swc_common::{
FileName, Mark, SourceMap,
};
use swc_ecma_ast::{EsVersion, Program};
use swc_ecma_loader::resolve::Resolution;
use swc_ecma_parser::{parse_file_as_module, Syntax, TsConfig};
use swc_ecma_transforms_base::{
helpers::{inject_helpers, Helpers, HELPERS},
Expand Down Expand Up @@ -273,10 +274,8 @@ impl NodeResolver {
None => bail!("not found"),
}
}
}

impl Resolve for NodeResolver {
fn resolve(&self, base: &FileName, target: &str) -> Result<FileName, Error> {
fn resolve_inner(&self, base: &FileName, target: &str) -> Result<FileName, Error> {
if let Ok(v) = Url::parse(target) {
return Ok(FileName::Custom(v.to_string()));
}
Expand Down Expand Up @@ -337,3 +336,13 @@ impl Resolve for NodeResolver {
.and_then(|p| self.wrap(p))
}
}

impl Resolve for NodeResolver {
fn resolve(&self, base: &FileName, module_specifier: &str) -> Result<Resolution, Error> {
self.resolve_inner(base, module_specifier)
.map(|filename| Resolution {
filename,
slug: None,
})
}
}
1 change: 1 addition & 0 deletions crates/swc_ecma_loader/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ serde = { version = "1", features = ["derive"] }
serde_json = { version = "1.0.64", optional = true }
tracing = "0.1.37"

swc_atoms = { version = "0.6.5", path = "../swc_atoms" }
swc_cached = { version = "0.3.18", optional = true, path = "../swc_cached" }
swc_common = { version = "0.33.14", path = "../swc_common" }

Expand Down
11 changes: 9 additions & 2 deletions crates/swc_ecma_loader/src/resolve.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
use std::sync::Arc;

use anyhow::Error;
use swc_atoms::Atom;
use swc_common::{
sync::{Send, Sync},
FileName,
};

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Resolution {
pub filename: FileName,
pub slug: Option<Atom>,
}

pub trait Resolve: Send + Sync {
fn resolve(&self, base: &FileName, module_specifier: &str) -> Result<FileName, Error>;
fn resolve(&self, base: &FileName, module_specifier: &str) -> Result<Resolution, Error>;
}

macro_rules! impl_ref {
Expand All @@ -16,7 +23,7 @@ macro_rules! impl_ref {
where
R: ?Sized + Resolve,
{
fn resolve(&self, base: &FileName, src: &str) -> Result<FileName, Error> {
fn resolve(&self, base: &FileName, src: &str) -> Result<Resolution, Error> {
(**self).resolve(base, src)
}
}
Expand Down
6 changes: 3 additions & 3 deletions crates/swc_ecma_loader/src/resolvers/lru.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ use lru::LruCache;
use parking_lot::Mutex;
use swc_common::FileName;

use crate::resolve::Resolve;
use crate::resolve::{Resolution, Resolve};

#[derive(Debug)]
pub struct CachingResolver<R>
where
R: Resolve,
{
cache: Mutex<LruCache<(FileName, String), FileName>>,
cache: Mutex<LruCache<(FileName, String), Resolution>>,
inner: R,
}

Expand Down Expand Up @@ -43,7 +43,7 @@ impl<R> Resolve for CachingResolver<R>
where
R: Resolve,
{
fn resolve(&self, base: &FileName, src: &str) -> Result<FileName, Error> {
fn resolve(&self, base: &FileName, src: &str) -> Result<Resolution, Error> {
{
let mut lock = self.cache.lock();
//
Expand Down
19 changes: 15 additions & 4 deletions crates/swc_ecma_loader/src/resolvers/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@ use swc_common::{
};
use tracing::{debug, trace, Level};

use crate::{resolve::Resolve, TargetEnv, NODE_BUILTINS};
use crate::{
resolve::{Resolution, Resolve},
TargetEnv, NODE_BUILTINS,
};

static PACKAGE: &str = "package.json";

Expand Down Expand Up @@ -409,10 +412,8 @@ impl NodeModulesResolver {

Ok(None)
}
}

impl Resolve for NodeModulesResolver {
fn resolve(&self, base: &FileName, target: &str) -> Result<FileName, Error> {
fn resolve_filename(&self, base: &FileName, target: &str) -> Result<FileName, Error> {
debug!(
"Resolving {} from {:#?} for {:#?}",
target, base, self.target_env
Expand Down Expand Up @@ -527,3 +528,13 @@ impl Resolve for NodeModulesResolver {
file_name
}
}

impl Resolve for NodeModulesResolver {
fn resolve(&self, base: &FileName, module_specifier: &str) -> Result<Resolution, Error> {
self.resolve_filename(base, module_specifier)
.map(|filename| Resolution {
filename,
slug: None,
})
}
}
Loading
Loading