Skip to content
2 changes: 1 addition & 1 deletion crates/swc_ecma_minifier/scripts/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export SWC_RUN=0

touch tests/compress.rs

UPDATE=1 cargo test -p swc_ecma_minifier -p swc --test size
RUST_LOG=off UPDATE=1 cargo test -p swc_ecma_minifier -p swc --test size
cargo test -p swc_ecma_minifier -p swc --no-fail-fast --test projects --test tsc --test compress --test mangle --features concurrent $@

# find ../swc/tests/ -type f -empty -delete
9 changes: 8 additions & 1 deletion crates/swc_ecma_minifier/src/compress/optimize/inline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,14 @@ impl Optimizer<'_> {

Expr::Lit(lit) => match lit {
Lit::Str(s) => {
if ref_count == 1 || s.value.len() <= 3 {
// If the string literal is declared without initializer and assigned
// once, we can inline it.
if (ref_count == 1
|| (ref_count == 2
&& usage.assign_count == 1
&& usage.flags.intersects(VarUsageInfoFlags::LAZY_INIT)))
|| s.value.len() <= 3
{
true
} else {
self.vars
Expand Down
6 changes: 6 additions & 0 deletions crates/swc_ecma_minifier/src/program_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ bitflags::bitflags! {
/// `a` in `foo(<a />)`
const USED_AS_JSX_CALLEE = 1 << 24;

/// The variable is declared without initializer.
const LAZY_INIT = 1 << 25;
}

#[derive(Debug, Default, Clone, Copy)]
Expand Down Expand Up @@ -581,6 +583,10 @@ impl VarDataLike for VarUsageInfo {
self.flags.insert(VarUsageInfoFlags::DECLARED_AS_FN_PARAM);
}

fn mark_as_lazy_init(&mut self) {
self.flags.insert(VarUsageInfoFlags::LAZY_INIT);
}

fn mark_declared_as_fn_decl(&mut self) {
self.flags.insert(VarUsageInfoFlags::DECLARED_AS_FN_DECL);
}
Expand Down
13 changes: 13 additions & 0 deletions crates/swc_ecma_minifier/src/util/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ pub trait ModuleItemExt:
{
fn as_module_decl(&self) -> Result<&ModuleDecl, &Stmt>;

fn as_module_decl_mut(&mut self) -> Result<&mut ModuleDecl, &mut Stmt>;

fn from_module_item(item: ModuleItem) -> Self;

fn into_module_item(self) -> ModuleItem {
Expand All @@ -46,6 +48,10 @@ impl ModuleItemExt for Stmt {
Err(self)
}

fn as_module_decl_mut(&mut self) -> Result<&mut ModuleDecl, &mut Stmt> {
Err(self)
}

fn from_module_item(item: ModuleItem) -> Self {
item.expect_stmt()
}
Expand All @@ -63,6 +69,13 @@ impl ModuleItemExt for ModuleItem {
}
}

fn as_module_decl_mut(&mut self) -> Result<&mut ModuleDecl, &mut Stmt> {
match self {
ModuleItem::ModuleDecl(v) => Ok(v),
ModuleItem::Stmt(v) => Err(v),
}
}

fn from_module_item(item: ModuleItem) -> Self {
item
}
Expand Down
14 changes: 7 additions & 7 deletions crates/swc_ecma_minifier/tests/benches-full/echarts.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */ /* global Reflect, Promise */ var ua, browser, firefox, ie, edge, weChat, style, mouseHandlerNames, pointerEventNameMap, pointerHandlerNames, classAttr, subTypeDefaulters, _super, mainType, creator, _ctx, _cachedFont, requestAnimationFrame, reCreateSeriesIndices, assertSeriesInitialized, initBase, _a, _b, _c, providerMethods, mountMethods, seriesType, nodeParsers, prepare, prepareView, updateDirectly, updateMethods, doConvertPixel, updateStreamModes, doDispatchAction, flushPendingActions, triggerUpdatedEvent, bindRenderedEvent, bindMouseEvent, clearColorPalette, render, renderComponents, renderSeries, performPostUpdateFuncs, createExtensionAPI, enableConnect, setTransitionOpt, markStatusToUpdate, applyChangedStates, defaultDimValueGetters, prepareInvertedIndex, getIndicesCtor, prepareStorage, getRawIndexWithoutIndices, getRawIndexWithIndices, getId, getIdNameFromStore, makeIdFromName, normalizeDimensions, validateDimensions, cloneListForMapAndSample, getInitialExtent, setItemDataAndSeriesIndex, transferProperties, checkNonStyleTansitionRefer, checkTransformPropRefer, extendStatics = function(d, b) {
***************************************************************************** */ /* global Reflect, Promise */ var ua, browser, firefox, ie, edge, weChat, style, mouseHandlerNames, pointerEventNameMap, pointerHandlerNames, classAttr, subTypeDefaulters, _super, creator, _ctx, _cachedFont, requestAnimationFrame, reCreateSeriesIndices, assertSeriesInitialized, initBase, _a, _b, _c, providerMethods, mountMethods, seriesType, nodeParsers, prepare, prepareView, updateDirectly, updateMethods, doConvertPixel, updateStreamModes, doDispatchAction, flushPendingActions, triggerUpdatedEvent, bindRenderedEvent, bindMouseEvent, clearColorPalette, render, renderComponents, renderSeries, performPostUpdateFuncs, createExtensionAPI, enableConnect, setTransitionOpt, markStatusToUpdate, applyChangedStates, defaultDimValueGetters, prepareInvertedIndex, getIndicesCtor, prepareStorage, getRawIndexWithoutIndices, getRawIndexWithIndices, getId, getIdNameFromStore, makeIdFromName, normalizeDimensions, validateDimensions, cloneListForMapAndSample, getInitialExtent, setItemDataAndSeriesIndex, transferProperties, checkNonStyleTansitionRefer, checkTransformPropRefer, extendStatics = function(d, b) {
return (extendStatics = Object.setPrototypeOf || ({
__proto__: []
}) instanceof Array && function(d, b) {
Expand Down Expand Up @@ -41507,7 +41507,7 @@
}; // If both `xAxisIndex` `xAxisId` not set, it means 'all'.
return null == setting.xAxisIndex && null == setting.xAxisId && (setting.xAxisIndex = 'all'), null == setting.yAxisIndex && null == setting.yAxisId && (setting.yAxisIndex = 'all'), setting;
}
mainType = 'dataZoom', creator = function(ecModel) {
creator = function(ecModel) {
var toolboxModel = ecModel.getComponent('toolbox', 0);
if (toolboxModel) {
var dzFeatureModel = toolboxModel.getModel([
Expand All @@ -41531,7 +41531,7 @@
};
newOpt[axisIndexPropName] = axisIndex, dzOptions.push(newOpt);
}
}, assert(null == internalOptionCreatorMap.get(mainType) && creator), internalOptionCreatorMap.set(mainType, creator);
}, assert(null == internalOptionCreatorMap.get('dataZoom') && creator), internalOptionCreatorMap.set('dataZoom', creator);
var TooltipModel = /** @class */ function(_super) {
function TooltipModel() {
var _this = null !== _super && _super.apply(this, arguments) || this;
Expand Down Expand Up @@ -41728,8 +41728,8 @@
// this.hide();
}, TooltipHTMLContent.prototype.show = function(tooltipModel, nearPointColor) {
clearTimeout(this._hideTimeout), clearTimeout(this._longHideTimeout);
var enableTransition, onlyFade, cssText, transitionDuration, backgroundColor, shadowBlur, shadowColor, shadowOffsetX, shadowOffsetY, textStyleModel, padding, boxShadow, transitionCurve, transitionOption, transitionText, cssText1, fontSize, color, shadowColor1, shadowBlur1, shadowOffsetX1, shadowOffsetY1, el = this.el, style = el.style, styleCoord = this._styleCoord;
el.innerHTML ? style.cssText = gCssText + (enableTransition = !this._firstShow, onlyFade = this._longHide, cssText = [], transitionDuration = tooltipModel.get('transitionDuration'), backgroundColor = tooltipModel.get('backgroundColor'), shadowBlur = tooltipModel.get('shadowBlur'), shadowColor = tooltipModel.get('shadowColor'), shadowOffsetX = tooltipModel.get('shadowOffsetX'), shadowOffsetY = tooltipModel.get('shadowOffsetY'), textStyleModel = tooltipModel.getModel('textStyle'), padding = getPaddingFromTooltipModel(tooltipModel, 'html'), boxShadow = shadowOffsetX + "px " + shadowOffsetY + "px " + shadowBlur + "px " + shadowColor, cssText.push('box-shadow:' + boxShadow), enableTransition && transitionDuration && cssText.push((transitionText = "opacity" + (transitionOption = " " + transitionDuration / 2 + "s " + (transitionCurve = 'cubic-bezier(0.23,1,0.32,1)')) + ",visibility" + transitionOption, onlyFade || (transitionOption = " " + transitionDuration + "s " + transitionCurve, transitionText += env.transformSupported ? "," + TRANSFORM_VENDOR + transitionOption : ",left" + transitionOption + ",top" + transitionOption), CSS_TRANSITION_VENDOR + ':' + transitionText)), backgroundColor && (env.canvasSupported ? cssText.push('background-color:' + backgroundColor) : (// for ie
var enableTransition, onlyFade, cssText, transitionDuration, backgroundColor, shadowBlur, shadowColor, shadowOffsetX, shadowOffsetY, textStyleModel, padding, boxShadow, transitionOption, transitionText, cssText1, fontSize, color, shadowColor1, shadowBlur1, shadowOffsetX1, shadowOffsetY1, el = this.el, style = el.style, styleCoord = this._styleCoord;
el.innerHTML ? style.cssText = gCssText + (enableTransition = !this._firstShow, onlyFade = this._longHide, cssText = [], transitionDuration = tooltipModel.get('transitionDuration'), backgroundColor = tooltipModel.get('backgroundColor'), shadowBlur = tooltipModel.get('shadowBlur'), shadowColor = tooltipModel.get('shadowColor'), shadowOffsetX = tooltipModel.get('shadowOffsetX'), shadowOffsetY = tooltipModel.get('shadowOffsetY'), textStyleModel = tooltipModel.getModel('textStyle'), padding = getPaddingFromTooltipModel(tooltipModel, 'html'), boxShadow = shadowOffsetX + "px " + shadowOffsetY + "px " + shadowBlur + "px " + shadowColor, cssText.push('box-shadow:' + boxShadow), enableTransition && transitionDuration && cssText.push((transitionText = "opacity" + (transitionOption = " " + transitionDuration / 2 + "s cubic-bezier(0.23,1,0.32,1)") + ",visibility" + transitionOption, onlyFade || (transitionOption = " " + transitionDuration + "s cubic-bezier(0.23,1,0.32,1)", transitionText += env.transformSupported ? "," + TRANSFORM_VENDOR + transitionOption : ",left" + transitionOption + ",top" + transitionOption), CSS_TRANSITION_VENDOR + ':' + transitionText)), backgroundColor && (env.canvasSupported ? cssText.push('background-color:' + backgroundColor) : (// for ie
cssText.push('background-color:#' + toHex(backgroundColor)), cssText.push('filter:alpha(opacity=70)'))), each([
'width',
'color',
Expand Down Expand Up @@ -45467,8 +45467,8 @@
}, SliderZoomView.prototype.dispose = function() {
this._clear(), _super.prototype.dispose.apply(this, arguments);
}, SliderZoomView.prototype._clear = function() {
(fn = this[fnAttr = '_dispatchZoomAction']) && fn[ORIGIN_METHOD] && (this[fnAttr] = fn[ORIGIN_METHOD]);
var fnAttr, fn, zr = this.api.getZr();
(fn = this._dispatchZoomAction) && fn[ORIGIN_METHOD] && (this._dispatchZoomAction = fn[ORIGIN_METHOD]);
var fn, zr = this.api.getZr();
zr.off('mousemove', this._onBrush), zr.off('mouseup', this._onBrushEnd);
}, SliderZoomView.prototype._buildView = function() {
var thisGroup = this.group;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const ErrorResponse = (statusCode, message) => {
return Response.json({
message
}, {
status: statusCode
});
}

export const unknownError = ErrorResponse(520, "Unknown error.");
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const unknownError = Response.json({
message: "Unknown error."
}, {
status: 520
});
Original file line number Diff line number Diff line change
Expand Up @@ -17717,7 +17717,7 @@
});
// EXTERNAL MODULE: ./node_modules/_@babel_runtime@7.15.4@@babel/runtime/helpers/esm/inheritsLoose.js + 1 modules
var inheritsLoose = __webpack_require__(48861), _react_17_0_2_react = __webpack_require__(59301), _prop_types_15_7_2_prop_types = __webpack_require__(68712), _prop_types_15_7_2_prop_types_default = /*#__PURE__*/ __webpack_require__.n(_prop_types_15_7_2_prop_types), esm_history = __webpack_require__(91520), commonjsGlobal = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof window ? window : void 0 !== __webpack_require__.g ? __webpack_require__.g : {}, index = _react_17_0_2_react.createContext || function(defaultValue, calculateChangedBits) {
var key, _Provider$childContex, _Consumer$contextType, contextProp = "__create-react-context-" + (commonjsGlobal[key = "__global_unique_id__"] = (commonjsGlobal[key] || 0) + 1) + "__", Provider = /*#__PURE__*/ function(_Component) {
var _Provider$childContex, _Consumer$contextType, contextProp = "__create-react-context-" + (commonjsGlobal.__global_unique_id__ = (commonjsGlobal.__global_unique_id__ || 0) + 1) + "__", Provider = /*#__PURE__*/ function(_Component) {
function Provider() {
var _this, value, handlers;
return _this = _Component.apply(this, arguments) || this, value = _this.props.value, handlers = [], _this.emitter = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,6 @@
* @param {number} length
* @return {string}
*/ function prefix(value, length) {
var search, search1;
switch((((length << 2 ^ Utility_charat(value, 0)) << 2 ^ Utility_charat(value, 1)) << 2 ^ Utility_charat(value, 2)) << 2 ^ Utility_charat(value, 3)){
// color-adjust
case 5103:
Expand Down Expand Up @@ -454,7 +453,7 @@
return replace(value, /(.+:)(.+)-([^]+)/, "$1" + WEBKIT + "$2-$3$1" + MOZ + (108 == Utility_charat(value, length + 3) ? "$3" : "$2-$3")) + value;
// (s)tretch
case 115:
return ~(search = "stretch", value.indexOf(search)) ? prefix(replace(value, "stretch", "fill-available"), length) + value : value;
return ~value.indexOf("stretch") ? prefix(replace(value, "stretch", "fill-available"), length) + value : value;
}
break;
// position: sticky
Expand All @@ -463,7 +462,7 @@
if (115 !== Utility_charat(value, length + 1)) break;
// display: (flex|inline-flex)
case 6444:
switch(Utility_charat(value, Utility_strlen(value) - 3 - (~(search1 = "!important", value.indexOf(search1)) && 10))){
switch(Utility_charat(value, Utility_strlen(value) - 3 - (~value.indexOf("!important") && 10))){
// stic(k)y
case 107:
return replace(value, ":", ":" + WEBKIT) + value;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7112,10 +7112,10 @@
function Engine() {}
return(// eslint-disable-next-line
Engine.prototype.compile = function(templateString, helper, ignorePrefix) {
var helper1, argName, str, nameSpace, helper2, ignorePrefix1, varCOunt, localKeys, isClass, singleSpace;
return void 0 === helper && (helper = {}), str = templateString, nameSpace = argName = 'data', helper2 = helper1 = helper, ignorePrefix1 = void 0, varCOunt = 0, localKeys = [], isClass = str.match(/class="([^"]+|)\s{2}/g), singleSpace = '', isClass && isClass.forEach(function(value) {
var helper1, str, nameSpace, helper2, ignorePrefix1, varCOunt, localKeys, isClass, singleSpace;
return void 0 === helper && (helper = {}), str = templateString, nameSpace = 'data', helper2 = helper1 = helper, ignorePrefix1 = void 0, varCOunt = 0, localKeys = [], isClass = str.match(/class="([^"]+|)\s{2}/g), singleSpace = '', isClass && isClass.forEach(function(value) {
singleSpace = value.replace(/\s\s+/g, ' '), str = str.replace(value, singleSpace);
}), Function(argName, "var str=\"" + str.replace(LINES, '').replace(DBL_QUOTED_STR, '\'$1\'').replace(exp, // eslint-disable-next-line
}), Function('data', "var str=\"" + str.replace(LINES, '').replace(DBL_QUOTED_STR, '\'$1\'').replace(exp, // eslint-disable-next-line
function(match, cnt, offset, matchStr) {
var matches = cnt.match(CALL_FUNCTION);
// matches to detect any function calls
Expand Down
2 changes: 1 addition & 1 deletion crates/swc_ecma_minifier/tests/libs-size.snapshot.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
| --- | --- | --- | --- |
| antd.js | 6.38 MiB | 2.06 MiB | 445.41 KiB |
| d3.js | 542.74 KiB | 261.44 KiB | 85.33 KiB |
| echarts.js | 3.41 MiB | 977.51 KiB | 314.17 KiB |
| echarts.js | 3.41 MiB | 977.53 KiB | 314.18 KiB |
| jquery.js | 280.89 KiB | 87.80 KiB | 30.21 KiB |
| lodash.js | 531.35 KiB | 68.91 KiB | 24.60 KiB |
| moment.js | 169.83 KiB | 57.39 KiB | 18.26 KiB |
Expand Down
Loading
Loading