1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
use std::{path::Path, sync::Arc};

use aok::Result;
use swc::{self, config, try_with_handler, BoolConfig, BoolOrDataConfig};
use swc_common::{SourceMap, GLOBALS};
use swc_ecma_ast::EsVersion;

pub fn minjs(fp: impl AsRef<Path>) -> Result<String> {
  let cm = Arc::<SourceMap>::default();

  let opts = config::Options {
    config: config::Config {
      minify: BoolConfig::new(Some(true)),
      jsc: config::JscConfig {
        target: Some(EsVersion::EsNext),
        minify: Some(config::JsMinifyOptions {
          compress: BoolOrDataConfig::from_bool(true),
          mangle: BoolOrDataConfig::from_bool(true),
          ..Default::default()
        }),
        ..Default::default()
      },
      ..Default::default()
    },
    ..Default::default()
  };

  let c = swc::Compiler::new(cm.clone());
  let output = GLOBALS.set(&Default::default(), || {
    try_with_handler(cm.clone(), Default::default(), |handler| {
      let fm = cm.load_file(fp.as_ref())?;
      c.process_js_file(fm, handler, &opts)
    })
  })?;

  Ok(output.code)
}