js.rs 2.2 KB

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