Skip to content
Closed
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
2 changes: 0 additions & 2 deletions Cargo.lock

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

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ insta = { version = "1.42.0", default-features = false }
itertools = { version = "0.14.0", default-features = false, features = ["use_std"] }
itoa = { version = "1.0.17", default-features = false }
json = { version = "0.12.4", default-features = false }
jsonc-parser = { version = "0.26.2", default-features = false, features = ["serde"] }
lightningcss = { version = "1.0.0-alpha.68", default-features = false, features = ["serde"] }
md4 = { version = "0.10.2", default-features = false }
memchr = { version = "2.7.6", default-features = false }
Expand Down
2 changes: 0 additions & 2 deletions crates/rspack_javascript_compiler/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,8 @@ version.workspace = true
anyhow = { workspace = true }
base64 = { workspace = true }
indoc = { workspace = true }
jsonc-parser = { workspace = true }
rustc-hash = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
swc_config = { workspace = true }
swc_core = { workspace = true, features = [
"__ecma",
Expand Down
233 changes: 46 additions & 187 deletions crates/rspack_javascript_compiler/src/compiler/transform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,20 @@
* Author Donny/강동윤
* Copyright (c)
*/
use std::{
env,
fs::File,
path::{Path, PathBuf},
sync::{Arc, LazyLock},
};
use std::{env, fs::File, path::PathBuf, sync::Arc};

use anyhow::{Context, bail};
use base64::prelude::*;
use indoc::formatdoc;
use jsonc_parser::parse_to_serde_value;
use rspack_error::Result;
use rspack_util::{itoa, source_map::SourceMapKind, swc::minify_file_comments};
use serde_json::error::Category;
use swc_config::{is_module::IsModule, merge::Merge};
use rspack_util::{source_map::SourceMapKind, swc::minify_file_comments};
use swc_config::is_module::IsModule;
pub use swc_core::base::config::Options as SwcOptions;
use swc_core::{
base::{
BoolOr,
config::{
BuiltInput, Config, ConfigFile, InputSourceMap, JsMinifyCommentOption, OutputCharset, Rc,
RootMode, SourceMapsConfig,
BuiltInput, Config, InputSourceMap, JsMinifyCommentOption, OutputCharset, SourceMapsConfig,
},
sourcemap,
},
Expand All @@ -38,7 +30,7 @@ use swc_core::{
ecma::{
ast::{EsVersion, Pass, Program},
parser::{
Syntax, parse_file_as_commonjs, parse_file_as_module, parse_file_as_program,
Syntax, TsSyntax, parse_file_as_commonjs, parse_file_as_module, parse_file_as_program,
parse_file_as_script,
},
transforms::base::helpers::{self, Helpers},
Expand Down Expand Up @@ -76,174 +68,6 @@ impl JavaScriptCompiler {
}
}

fn parse_swcrc(s: &str) -> Result<Rc, anyhow::Error> {
fn convert_json_err(e: serde_json::Error) -> anyhow::Error {
let line = e.line();
let column = e.column();

let msg = match e.classify() {
Category::Io => "io error",
Category::Syntax => "syntax error",
Category::Data => "unmatched data",
Category::Eof => "unexpected eof",
};
let mut line_buffer = itoa::Buffer::new();
let line_str = line_buffer.format(line);
let mut column_buffer = itoa::Buffer::new();
let column_str = column_buffer.format(column);
anyhow::Error::new(e).context(format!(
"failed to deserialize .swcrc (json) file: {msg}: {line_str}:{column_str}"
))
}

let v = parse_to_serde_value(
s.trim_start_matches('\u{feff}'),
&jsonc_parser::ParseOptions {
allow_comments: true,
allow_trailing_commas: true,
allow_loose_object_property_names: false,
},
)?
.ok_or_else(|| anyhow::Error::msg("failed to deserialize empty .swcrc (json) file"))?;

if let Ok(rc) = serde_json::from_value(v.clone()) {
return Ok(rc);
}

serde_json::from_value(v)
.map(Rc::Single)
.map_err(convert_json_err)
}

fn find_swcrc(path: &Path, root: &Path, root_mode: RootMode) -> Option<PathBuf> {
let mut parent = path.parent();
while let Some(dir) = parent {
let swcrc = dir.join(".swcrc");

if swcrc.exists() {
return Some(swcrc);
}

if dir == root && root_mode == RootMode::Root {
break;
}
parent = dir.parent();
}

None
}

fn load_swcrc(path: &Path) -> Result<Rc, anyhow::Error> {
let content = std::fs::read_to_string(path).context("failed to read config (.swcrc) file")?;

parse_swcrc(&content)
}

fn read_config(opts: &SwcOptions, name: &FileName) -> Result<Option<Config>, anyhow::Error> {
static CUR_DIR: LazyLock<PathBuf> = LazyLock::new(|| {
if cfg!(target_arch = "wasm32") {
PathBuf::new()
} else {
::std::env::current_dir().expect("should be available")
}
});

let res: Result<_, anyhow::Error> = {
let SwcOptions {
root,
root_mode,
swcrc,
config_file,
..
} = opts;

let root = root.as_ref().unwrap_or(&CUR_DIR);

let swcrc_path = match config_file {
Some(ConfigFile::Str(s)) => Some(PathBuf::from(s.clone())),
_ => {
if *swcrc {
if let FileName::Real(path) = name {
find_swcrc(path, root, *root_mode)
} else {
None
}
} else {
None
}
}
};

let config_file = match swcrc_path.as_deref() {
Some(s) => Some(load_swcrc(s)?),
_ => None,
};
let filename_path = match name {
FileName::Real(p) => Some(&**p),
_ => None,
};

if let Some(filename_path) = filename_path {
if let Some(config) = config_file {
let dir = swcrc_path
.as_deref()
.and_then(|p| p.parent())
.expect(".swcrc path should have parent dir");

let mut config = config
.into_config(Some(filename_path))
.context("failed to process config file")?;

if let Some(c) = &mut config
&& c.jsc.base_url != PathBuf::new()
{
let joined = dir.join(&c.jsc.base_url);
c.jsc.base_url = if cfg!(target_os = "windows") && c.jsc.base_url.as_os_str() == "." {
dir.canonicalize().with_context(|| {
format!(
"failed to canonicalize base url using the path of \
.swcrc\nDir: {}\n(Used logic for windows)",
dir.display(),
)
})?
} else {
joined.canonicalize().with_context(|| {
format!(
"failed to canonicalize base url using the path of \
.swcrc\nPath: {}\nDir: {}\nbaseUrl: {}",
joined.display(),
dir.display(),
c.jsc.base_url.display()
)
})?
};
}

return Ok(config);
}

let config_file = config_file.unwrap_or_default();
let config = config_file.into_config(Some(filename_path))?;

return Ok(config);
}

let config = match config_file {
Some(config_file) => config_file.into_config(None)?,
None => Rc::default().into_config(None)?,
};

match config {
Some(config) => Ok(Some(config)),
None => {
anyhow::bail!("no config matched for file ({name})")
}
}
};

res.with_context(|| format!("failed to read .swcrc file for input file at `{name}`"))
}

struct JavaScriptTransformer<'a> {
cm: Arc<SourceMap>,
fm: Arc<SourceFile>,
Expand All @@ -270,13 +94,10 @@ impl<'a> JavaScriptTransformer<'a> {
options.unresolved_mark = Some(unresolved_mark);
});

let config = get_swc_config_from_file(&fm.name);
let comments = SingleThreadedComments::default();
let config = read_config(&options, &fm.name)?
.ok_or_else(|| rspack_error::error!("cannot process file because it's ignored by .swcrc"))?;

let helpers = GLOBALS.set(&compiler.globals, || {
let mut external_helpers = options.config.jsc.external_helpers;
external_helpers.merge(config.jsc.external_helpers);
let external_helpers = options.config.jsc.external_helpers;
Helpers::new(external_helpers.into())
});

Expand All @@ -286,8 +107,8 @@ impl<'a> JavaScriptTransformer<'a> {
javascript_compiler: compiler,
options,
helpers,
config,
comments,
config,
})
}

Expand Down Expand Up @@ -651,3 +472,41 @@ impl<'a> JavaScriptTransformer<'a> {
}
}
}

fn get_swc_config_from_file(filename: &FileName) -> Config {
let filename_path = match filename {
FileName::Real(p) => Some(p.as_path()),
_ => return Config::default(),
};

let filename_ext = match filename_path {
Some(p) => p.extension().and_then(|ext| ext.to_str()),
None => return Config::default(),
};

let mut config = Config::default();
match filename_ext {
Some("tsx") => {
config.jsc.syntax = Some(Syntax::Typescript(TsSyntax {
tsx: true,
..Default::default()
}))
}
Some("cts" | "mts") => {
config.jsc.syntax = Some(Syntax::Typescript(TsSyntax {
tsx: false,
disallow_ambiguous_jsx_like: true,
..Default::default()
}))
}
Some("ts") => {
config.jsc.syntax = Some(Syntax::Typescript(TsSyntax {
tsx: false,
..Default::default()
}))
}
_ => {}
}

config
}
Loading