2022-01-15 10:43:34 +03:00
|
|
|
#![allow(clippy::needless_update)]
|
|
|
|
|
2021-10-08 10:47:01 +03:00
|
|
|
/// Use memory allocator
|
|
|
|
extern crate swc_node_base;
|
|
|
|
|
|
|
|
use anyhow::{bail, Error};
|
|
|
|
use path_clean::PathClean;
|
|
|
|
use std::{
|
|
|
|
collections::HashMap,
|
|
|
|
env, fs,
|
|
|
|
path::{Path, PathBuf},
|
2021-12-21 12:19:33 +03:00
|
|
|
time::{Duration, Instant},
|
2021-10-08 10:47:01 +03:00
|
|
|
};
|
|
|
|
use swc_atoms::js_word;
|
|
|
|
use swc_bundler::{Bundle, Bundler, Load, ModuleData, ModuleRecord, Resolve};
|
|
|
|
use swc_common::{
|
|
|
|
errors::{ColorConfig, Handler},
|
|
|
|
sync::Lrc,
|
2021-12-21 12:19:33 +03:00
|
|
|
FileName, Globals, Mark, SourceMap, Span, GLOBALS,
|
2021-10-08 10:47:01 +03:00
|
|
|
};
|
|
|
|
use swc_ecma_ast::*;
|
2021-12-21 12:19:33 +03:00
|
|
|
use swc_ecma_codegen::{
|
|
|
|
text_writer::{omit_trailing_semi, JsWriter, WriteJs},
|
|
|
|
Emitter,
|
|
|
|
};
|
2021-11-11 14:00:46 +03:00
|
|
|
use swc_ecma_loader::{
|
|
|
|
resolvers::{lru::CachingResolver, node::NodeModulesResolver},
|
|
|
|
TargetEnv,
|
|
|
|
};
|
2021-12-21 12:19:33 +03:00
|
|
|
use swc_ecma_minifier::option::{
|
|
|
|
CompressOptions, ExtraOptions, MangleOptions, MinifyOptions, TopLevelOptions,
|
|
|
|
};
|
2021-10-08 10:47:01 +03:00
|
|
|
use swc_ecma_parser::{lexer::Lexer, EsConfig, Parser, StringInput, Syntax};
|
2021-12-21 12:19:33 +03:00
|
|
|
use swc_ecma_transforms_base::fixer::fixer;
|
|
|
|
use swc_ecma_visit::VisitMutWith;
|
2021-10-08 10:47:01 +03:00
|
|
|
|
2021-12-21 12:19:33 +03:00
|
|
|
fn print_bundles(cm: Lrc<SourceMap>, modules: Vec<Bundle>, minify: bool) {
|
2021-10-08 10:47:01 +03:00
|
|
|
for bundled in modules {
|
|
|
|
let code = {
|
|
|
|
let mut buf = vec![];
|
|
|
|
|
|
|
|
{
|
2021-12-21 12:19:33 +03:00
|
|
|
let wr = JsWriter::new(cm.clone(), "\n", &mut buf, None);
|
2021-10-08 10:47:01 +03:00
|
|
|
let mut emitter = Emitter {
|
|
|
|
cfg: swc_ecma_codegen::Config {
|
2021-12-21 12:19:33 +03:00
|
|
|
minify,
|
2021-10-08 10:47:01 +03:00
|
|
|
..Default::default()
|
|
|
|
},
|
|
|
|
cm: cm.clone(),
|
|
|
|
comments: None,
|
2021-12-21 12:19:33 +03:00
|
|
|
wr: if minify {
|
|
|
|
Box::new(omit_trailing_semi(wr)) as Box<dyn WriteJs>
|
|
|
|
} else {
|
|
|
|
Box::new(wr) as Box<dyn WriteJs>
|
|
|
|
},
|
2021-10-08 10:47:01 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
emitter.emit_module(&bundled.module).unwrap();
|
|
|
|
}
|
|
|
|
|
|
|
|
String::from_utf8_lossy(&buf).to_string()
|
|
|
|
};
|
|
|
|
|
2021-10-15 06:49:37 +03:00
|
|
|
#[cfg(feature = "concurrent")]
|
|
|
|
rayon::spawn(move || drop(bundled));
|
|
|
|
|
2021-12-21 12:19:33 +03:00
|
|
|
println!("Created output.js ({}kb)", code.len() / 1024);
|
2021-10-08 10:47:01 +03:00
|
|
|
fs::write("output.js", &code).unwrap();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-21 12:19:33 +03:00
|
|
|
fn do_test(_entry: &Path, entries: HashMap<String, FileName>, inline: bool, minify: bool) {
|
2021-10-08 10:47:01 +03:00
|
|
|
testing::run_test2(false, |cm, _| {
|
2021-10-15 06:49:37 +03:00
|
|
|
let start = Instant::now();
|
|
|
|
|
|
|
|
let globals = Box::leak(Box::new(Globals::default()));
|
|
|
|
let mut bundler = Bundler::new(
|
|
|
|
globals,
|
2021-10-08 10:47:01 +03:00
|
|
|
cm.clone(),
|
|
|
|
Loader { cm: cm.clone() },
|
2021-10-15 06:49:37 +03:00
|
|
|
CachingResolver::new(
|
|
|
|
4096,
|
2022-01-25 00:21:06 +03:00
|
|
|
NodeModulesResolver::new(TargetEnv::Node, Default::default(), true),
|
2021-10-15 06:49:37 +03:00
|
|
|
),
|
2021-10-08 10:47:01 +03:00
|
|
|
swc_bundler::Config {
|
2021-12-21 15:39:35 +03:00
|
|
|
require: false,
|
2021-10-08 10:47:01 +03:00
|
|
|
disable_inliner: !inline,
|
|
|
|
external_modules: Default::default(),
|
2021-12-21 12:19:33 +03:00
|
|
|
disable_fixer: minify,
|
|
|
|
disable_hygiene: minify,
|
2021-12-22 20:53:02 +03:00
|
|
|
disable_dce: false,
|
2021-10-08 10:47:01 +03:00
|
|
|
module: Default::default(),
|
|
|
|
},
|
|
|
|
Box::new(Hook),
|
|
|
|
);
|
|
|
|
|
2021-12-21 12:19:33 +03:00
|
|
|
let mut modules = bundler
|
2021-10-08 10:47:01 +03:00
|
|
|
.bundle(entries)
|
|
|
|
.map_err(|err| println!("{:?}", err))?;
|
|
|
|
println!("Bundled as {} modules", modules.len());
|
|
|
|
|
2021-10-15 06:49:37 +03:00
|
|
|
#[cfg(feature = "concurrent")]
|
|
|
|
rayon::spawn(move || {
|
|
|
|
drop(bundler);
|
|
|
|
});
|
|
|
|
|
|
|
|
{
|
|
|
|
let dur = start.elapsed();
|
2021-12-21 12:19:33 +03:00
|
|
|
println!("Bundler.bundle() took {}", to_ms(dur));
|
2021-10-15 06:49:37 +03:00
|
|
|
}
|
|
|
|
|
2021-10-08 10:47:01 +03:00
|
|
|
let error = false;
|
2021-12-21 12:19:33 +03:00
|
|
|
if minify {
|
|
|
|
let start = Instant::now();
|
|
|
|
|
|
|
|
modules = modules
|
|
|
|
.into_iter()
|
|
|
|
.map(|mut b| {
|
2022-01-13 17:06:11 +03:00
|
|
|
GLOBALS.set(globals, || {
|
2021-12-21 12:19:33 +03:00
|
|
|
b.module = swc_ecma_minifier::optimize(
|
|
|
|
b.module,
|
|
|
|
cm.clone(),
|
|
|
|
None,
|
|
|
|
None,
|
|
|
|
&MinifyOptions {
|
|
|
|
compress: Some(CompressOptions {
|
|
|
|
top_level: Some(TopLevelOptions { functions: true }),
|
|
|
|
..Default::default()
|
|
|
|
}),
|
|
|
|
mangle: Some(MangleOptions {
|
|
|
|
top_level: true,
|
|
|
|
..Default::default()
|
|
|
|
}),
|
|
|
|
..Default::default()
|
|
|
|
},
|
|
|
|
&ExtraOptions {
|
|
|
|
top_level_mark: Mark::fresh(Mark::root()),
|
|
|
|
},
|
|
|
|
);
|
|
|
|
b.module.visit_mut_with(&mut fixer(None));
|
|
|
|
b
|
|
|
|
})
|
|
|
|
})
|
|
|
|
.collect();
|
|
|
|
|
|
|
|
let dur = start.elapsed();
|
|
|
|
println!("Minification took {}", to_ms(dur));
|
|
|
|
}
|
2021-10-08 10:47:01 +03:00
|
|
|
|
2021-10-15 06:49:37 +03:00
|
|
|
{
|
2022-01-13 17:06:11 +03:00
|
|
|
let cm = cm;
|
2021-12-21 12:19:33 +03:00
|
|
|
print_bundles(cm, modules, minify);
|
2021-10-15 06:49:37 +03:00
|
|
|
}
|
2021-10-08 10:47:01 +03:00
|
|
|
|
|
|
|
if error {
|
|
|
|
return Err(());
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
})
|
|
|
|
.expect("failed to process a module");
|
|
|
|
}
|
|
|
|
|
2021-12-21 12:19:33 +03:00
|
|
|
fn to_ms(dur: Duration) -> String {
|
|
|
|
format!("{}ms", dur.as_millis())
|
|
|
|
}
|
|
|
|
|
2021-10-08 10:47:01 +03:00
|
|
|
fn main() -> Result<(), Error> {
|
2021-12-21 12:19:33 +03:00
|
|
|
let minify = env::var("MINIFY").unwrap_or_else(|_| "0".to_string()) == "1";
|
|
|
|
|
2021-10-08 10:47:01 +03:00
|
|
|
let main_file = env::args().nth(1).unwrap();
|
|
|
|
let mut entries = HashMap::default();
|
|
|
|
entries.insert("main".to_string(), FileName::Real(main_file.clone().into()));
|
|
|
|
|
|
|
|
let start = Instant::now();
|
2021-12-21 12:19:33 +03:00
|
|
|
do_test(Path::new(&main_file), entries, false, minify);
|
2021-10-08 10:47:01 +03:00
|
|
|
let dur = start.elapsed();
|
2021-12-21 12:19:33 +03:00
|
|
|
println!("Took {}", to_ms(dur));
|
2021-10-08 10:47:01 +03:00
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
struct Hook;
|
|
|
|
|
|
|
|
impl swc_bundler::Hook for Hook {
|
|
|
|
fn get_import_meta_props(
|
|
|
|
&self,
|
|
|
|
span: Span,
|
|
|
|
module_record: &ModuleRecord,
|
|
|
|
) -> Result<Vec<KeyValueProp>, Error> {
|
|
|
|
Ok(vec![
|
|
|
|
KeyValueProp {
|
|
|
|
key: PropName::Ident(Ident::new(js_word!("url"), span)),
|
|
|
|
value: Box::new(Expr::Lit(Lit::Str(Str {
|
|
|
|
span,
|
|
|
|
value: module_record.file_name.to_string().into(),
|
|
|
|
has_escape: false,
|
|
|
|
kind: Default::default(),
|
|
|
|
}))),
|
|
|
|
},
|
|
|
|
KeyValueProp {
|
|
|
|
key: PropName::Ident(Ident::new(js_word!("main"), span)),
|
|
|
|
value: Box::new(if module_record.is_entry {
|
|
|
|
Expr::Member(MemberExpr {
|
|
|
|
span,
|
2022-01-10 16:54:42 +03:00
|
|
|
obj: Box::new(Expr::MetaProp(MetaPropExpr {
|
|
|
|
span,
|
|
|
|
kind: MetaPropKind::ImportMeta,
|
|
|
|
})),
|
|
|
|
prop: MemberProp::Ident(Ident::new(js_word!("main"), span)),
|
2021-10-08 10:47:01 +03:00
|
|
|
})
|
|
|
|
} else {
|
|
|
|
Expr::Lit(Lit::Bool(Bool { span, value: false }))
|
|
|
|
}),
|
|
|
|
},
|
|
|
|
])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct Loader {
|
|
|
|
pub cm: Lrc<SourceMap>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Load for Loader {
|
|
|
|
fn load(&self, f: &FileName) -> Result<ModuleData, Error> {
|
|
|
|
let fm = match f {
|
2022-01-13 17:06:11 +03:00
|
|
|
FileName::Real(path) => self.cm.load_file(path)?,
|
2021-10-08 10:47:01 +03:00
|
|
|
_ => unreachable!(),
|
|
|
|
};
|
|
|
|
|
|
|
|
let lexer = Lexer::new(
|
|
|
|
Syntax::Es(EsConfig {
|
|
|
|
..Default::default()
|
|
|
|
}),
|
|
|
|
EsVersion::Es2020,
|
|
|
|
StringInput::from(&*fm),
|
|
|
|
None,
|
|
|
|
);
|
|
|
|
|
|
|
|
let mut parser = Parser::new_from(lexer);
|
|
|
|
let module = parser.parse_module().unwrap_or_else(|err| {
|
|
|
|
let handler =
|
|
|
|
Handler::with_tty_emitter(ColorConfig::Always, false, false, Some(self.cm.clone()));
|
|
|
|
err.into_diagnostic(&handler).emit();
|
|
|
|
panic!("failed to parse")
|
|
|
|
});
|
|
|
|
|
|
|
|
Ok(ModuleData {
|
|
|
|
fm,
|
|
|
|
module,
|
|
|
|
helpers: Default::default(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct NodeResolver;
|
|
|
|
|
|
|
|
static EXTENSIONS: &[&str] = &["ts", "tsx", "js", "jsx", "json", "node"];
|
|
|
|
|
|
|
|
impl NodeResolver {
|
|
|
|
fn wrap(&self, path: PathBuf) -> Result<FileName, Error> {
|
|
|
|
let path = path.clean();
|
|
|
|
Ok(FileName::Real(path))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Resolve a path as a file. If `path` refers to a file, it is
|
|
|
|
/// returned; otherwise the `path` + each extension is tried.
|
|
|
|
fn resolve_as_file(&self, path: &Path) -> Result<PathBuf, Error> {
|
|
|
|
// 1. If X is a file, load X as JavaScript text.
|
|
|
|
if path.is_file() {
|
|
|
|
return Ok(path.to_path_buf());
|
|
|
|
}
|
|
|
|
|
|
|
|
for ext in EXTENSIONS {
|
|
|
|
let ext_path = path.with_extension(ext);
|
|
|
|
if ext_path.is_file() {
|
|
|
|
return Ok(ext_path);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
bail!("file not found: {}", path.display())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Resolve a path as a directory, using the "main" key from a
|
|
|
|
/// package.json file if it exists, or resolving to the
|
|
|
|
/// index.EXT file if it exists.
|
2022-01-14 01:20:45 +03:00
|
|
|
fn resolve_as_directory(&self, path: &Path) -> Result<PathBuf, Error> {
|
2021-10-08 10:47:01 +03:00
|
|
|
// 1. If X/package.json is a file, use it.
|
|
|
|
let pkg_path = path.join("package.json");
|
|
|
|
if pkg_path.is_file() {
|
|
|
|
let main = self.resolve_package_main(&pkg_path);
|
|
|
|
if main.is_ok() {
|
|
|
|
return main;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// 2. LOAD_INDEX(X)
|
|
|
|
self.resolve_index(path)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Resolve using the package.json "main" key.
|
2022-01-14 01:20:45 +03:00
|
|
|
fn resolve_package_main(&self, _: &Path) -> Result<PathBuf, Error> {
|
2021-10-08 10:47:01 +03:00
|
|
|
bail!("package.json is not supported")
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Resolve a directory to its index.EXT.
|
2022-01-14 01:20:45 +03:00
|
|
|
fn resolve_index(&self, path: &Path) -> Result<PathBuf, Error> {
|
2021-10-08 10:47:01 +03:00
|
|
|
// 1. If X/index.js is a file, load X/index.js as JavaScript text.
|
|
|
|
// 2. If X/index.json is a file, parse X/index.json to a JavaScript object.
|
|
|
|
// 3. If X/index.node is a file, load X/index.node as binary addon.
|
|
|
|
for ext in EXTENSIONS {
|
|
|
|
let ext_path = path.join(format!("index.{}", ext));
|
|
|
|
if ext_path.is_file() {
|
|
|
|
return Ok(ext_path);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
bail!("index not found: {}", path.display())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Resolve by walking up node_modules folders.
|
|
|
|
fn resolve_node_modules(&self, base_dir: &Path, target: &str) -> Result<PathBuf, Error> {
|
|
|
|
let node_modules = base_dir.join("node_modules");
|
|
|
|
if node_modules.is_dir() {
|
|
|
|
let path = node_modules.join(target);
|
|
|
|
let result = self
|
|
|
|
.resolve_as_file(&path)
|
|
|
|
.or_else(|_| self.resolve_as_directory(&path));
|
|
|
|
if result.is_ok() {
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
match base_dir.parent() {
|
|
|
|
Some(parent) => self.resolve_node_modules(parent, target),
|
|
|
|
None => bail!("not found"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Resolve for NodeResolver {
|
|
|
|
fn resolve(&self, base: &FileName, target: &str) -> Result<FileName, Error> {
|
|
|
|
let base = match base {
|
|
|
|
FileName::Real(v) => v,
|
|
|
|
_ => bail!("node-resolver supports only files"),
|
|
|
|
};
|
|
|
|
|
|
|
|
// Absolute path
|
2022-01-13 17:06:11 +03:00
|
|
|
if target.starts_with('/') {
|
2021-10-08 10:47:01 +03:00
|
|
|
let base_dir = &Path::new("/");
|
|
|
|
|
|
|
|
let path = base_dir.join(target);
|
|
|
|
return self
|
|
|
|
.resolve_as_file(&path)
|
|
|
|
.or_else(|_| self.resolve_as_directory(&path))
|
|
|
|
.and_then(|p| self.wrap(p));
|
|
|
|
}
|
|
|
|
|
|
|
|
let cwd = &Path::new(".");
|
2022-01-13 17:06:11 +03:00
|
|
|
let mut base_dir = base.parent().unwrap_or(cwd);
|
2021-10-08 10:47:01 +03:00
|
|
|
|
|
|
|
if target.starts_with("./") || target.starts_with("../") {
|
|
|
|
let win_target;
|
|
|
|
let target = if cfg!(target_os = "windows") {
|
2022-02-08 13:50:22 +03:00
|
|
|
let t = if let Some(s) = target.strip_prefix("./") {
|
|
|
|
s
|
2021-10-08 10:47:01 +03:00
|
|
|
} else {
|
|
|
|
base_dir = base_dir.parent().unwrap();
|
|
|
|
&target[3..]
|
|
|
|
};
|
2022-02-08 13:50:22 +03:00
|
|
|
win_target = t.replace('/', "\\");
|
2021-10-08 10:47:01 +03:00
|
|
|
&*win_target
|
|
|
|
} else {
|
|
|
|
target
|
|
|
|
};
|
|
|
|
|
|
|
|
let path = base_dir.join(target);
|
|
|
|
return self
|
|
|
|
.resolve_as_file(&path)
|
|
|
|
.or_else(|_| self.resolve_as_directory(&path))
|
|
|
|
.and_then(|p| self.wrap(p));
|
|
|
|
}
|
|
|
|
|
|
|
|
self.resolve_node_modules(base_dir, target)
|
|
|
|
.and_then(|p| self.wrap(p))
|
|
|
|
}
|
|
|
|
}
|