js.rs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. use std::io::Read;
  2. use std::path::Path;
  3. use std::sync::Arc;
  4. use anyhow::Context;
  5. use manganis_core::JsAssetOptions;
  6. use swc::{config::JsMinifyOptions, try_with_handler, BoolOrDataConfig};
  7. use swc_common::{sync::Lrc, FileName};
  8. use swc_common::{SourceMap, GLOBALS};
  9. pub(crate) fn minify_js(source: &Path) -> anyhow::Result<String> {
  10. let mut source_file = std::fs::File::open(source)?;
  11. let cm = Arc::new(SourceMap::default());
  12. let mut js = String::new();
  13. source_file.read_to_string(&mut js)?;
  14. let c = swc::Compiler::new(cm.clone());
  15. let output = GLOBALS
  16. .set(&Default::default(), || {
  17. try_with_handler(cm.clone(), Default::default(), |handler| {
  18. let filename = Lrc::new(FileName::Real(source.to_path_buf()));
  19. let fm = cm.new_source_file(filename, js.to_string());
  20. c.minify(
  21. fm,
  22. handler,
  23. &JsMinifyOptions {
  24. compress: BoolOrDataConfig::from_bool(true),
  25. mangle: BoolOrDataConfig::from_bool(true),
  26. ..Default::default()
  27. },
  28. )
  29. .context("failed to minify javascript")
  30. })
  31. })
  32. .map(|output| output.code);
  33. match output {
  34. Ok(output) => Ok(output),
  35. Err(err) => {
  36. tracing::error!("Failed to minify javascript: {}", err);
  37. Ok(js)
  38. }
  39. }
  40. }
  41. pub(crate) fn process_js(
  42. js_options: &JsAssetOptions,
  43. source: &Path,
  44. output_path: &Path,
  45. ) -> anyhow::Result<()> {
  46. let js = if js_options.minified() {
  47. minify_js(source)?
  48. } else {
  49. let mut source_file = std::fs::File::open(source)?;
  50. let mut source = String::new();
  51. source_file.read_to_string(&mut source)?;
  52. source
  53. };
  54. std::fs::write(output_path, js).with_context(|| {
  55. format!(
  56. "Failed to write js to output location: {}",
  57. output_path.display()
  58. )
  59. })?;
  60. Ok(())
  61. }