|
| 1 | +use std::fs::File; |
| 2 | + |
| 3 | +use super::PluginConfig; |
| 4 | +use crate::bundle_graph::BundleGraph; |
| 5 | +use crate::types::Bundle; |
| 6 | +use crate::types::SourceMap; |
| 7 | + |
| 8 | +pub struct OptimizeContext<'a> { |
| 9 | + pub bundle: &'a Bundle, |
| 10 | + pub bundle_graph: &'a BundleGraph, |
| 11 | + pub contents: &'a File, // TODO We may want this to be a String or File later |
| 12 | + pub map: Option<&'a SourceMap>, |
| 13 | + // TODO getSourceMapReference? |
| 14 | +} |
| 15 | + |
| 16 | +pub struct OptimizedBundle { |
| 17 | + pub contents: File, |
| 18 | + // TODO ast, map, type |
| 19 | +} |
| 20 | + |
1 | 21 | /// Optimises a bundle
|
2 | 22 | ///
|
3 | 23 | /// Optimizers are commonly used to implement minification, tree shaking, dead code elimination,
|
|
8 | 28 | /// Multiple optimizer plugins may run in series, and the result of each optimizer is passed to
|
9 | 29 | /// the next.
|
10 | 30 | ///
|
11 |
| -pub trait OptimizerPlugin: Send + Sync {} |
| 31 | +pub trait OptimizerPlugin: Send + Sync { |
| 32 | + /// A hook designed to setup config needed for optimizing bundles |
| 33 | + /// |
| 34 | + /// This function will run once, shortly after the plugin is initialised. |
| 35 | + /// |
| 36 | + fn load_config(&mut self, config: &PluginConfig) -> Result<(), anyhow::Error>; |
| 37 | + |
| 38 | + /// Transforms the contents of a bundle and its source map |
| 39 | + fn optimize( |
| 40 | + &mut self, |
| 41 | + config: &PluginConfig, |
| 42 | + ctx: OptimizeContext, |
| 43 | + ) -> Result<OptimizedBundle, anyhow::Error>; |
| 44 | +} |
| 45 | + |
| 46 | +#[cfg(test)] |
| 47 | +mod tests { |
| 48 | + use super::*; |
| 49 | + |
| 50 | + struct TestOptimizerPlugin {} |
| 51 | + |
| 52 | + impl OptimizerPlugin for TestOptimizerPlugin { |
| 53 | + fn load_config(&mut self, _config: &PluginConfig) -> Result<(), anyhow::Error> { |
| 54 | + todo!() |
| 55 | + } |
| 56 | + |
| 57 | + fn optimize( |
| 58 | + &mut self, |
| 59 | + _config: &PluginConfig, |
| 60 | + _ctx: OptimizeContext, |
| 61 | + ) -> Result<OptimizedBundle, anyhow::Error> { |
| 62 | + todo!() |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + #[test] |
| 67 | + fn can_be_defined_in_dyn_vec() { |
| 68 | + let mut optimizers = Vec::<Box<dyn OptimizerPlugin>>::new(); |
| 69 | + |
| 70 | + optimizers.push(Box::new(TestOptimizerPlugin {})); |
| 71 | + |
| 72 | + assert_eq!(optimizers.len(), 1); |
| 73 | + } |
| 74 | +} |
0 commit comments